LeetCode 344. Reverse String
Write a function that reverses a string. The input string is given as an array of characters s.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
method: 反向双指针
两个指针从两边同时向中间遍历,不断交换元素void reverseString(vector<char>& s) {
int l = 0, r = s.size() - 1;
while (l < r) {
swap(s[l], s[r]);
l++;
r--;
}
}
LeetCode 345. Reverse Vowels of a String
Given a string s, reverse only all the vowels in the string and return it.
The vowels are ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’, and they can appear in both cases.
Example 1:
Input: s = "hello"
Output: "holle"
method: 集合存储元音字母
string reverseVowels(string s) {
set<char> st{'a','e','i','o','u','A','E','I','O','U'};
int l = 0, r = s.size() - 1;
while (l < r) {
while (l < r && st.find(s[l]) == st.end()) l++;
while (l < r && st.find(s[r]) == st.end()) r--;
swap(s[l], s[r]);
l++;
r--;
}
return s;
}