Reverse Vowels of a String

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 lower and upper cases, more than once.

Example 1:

1
2
Input: s = "hello"
Output: "holle"

Example 2:

1
2
Input: s = "leetcode"
Output: "leotcede"

双指针:

时间复杂度:O(n)

空间复杂度:O(10)

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
string reverseVowels(string s) {
unordered_set<int> set = { 'a','e','i','o','u','A','E','I','O','U' };
for (int left = 0, right = s.size() - 1;
left < right; left++, right--) {
while(!set.count(s[left])&&(left < right))left++;
while(!set.count(s[right])&&(left < right))right--;
swap(s[left], s[right]);
}
return s;
}
};