Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello" Output: "holle"
Example 2:
Input: "leetcode" Output: "leotcede"
Note:
The vowels does not include the letter "y".
这道题的关键在于如何同时交换两个元音字母。我们这里采取的方法是分别找到左边和右边的元音字母然后交换。
另外,我们这里使用了用数组来“哈希”字母的trick。
class Solution {
public:
string reverseVowels(string s) {
vector<int> v(256, 0);
v['a'] = 1;
v['e'] = 1;
v['i'] = 1;
v['o'] = 1;
v['u'] = 1;
v['A'] = 1;
v['E'] = 1;
v['I'] = 1;
v['O'] = 1;
v['U'] = 1;
int left = 0, right = int(s.size() - 1);
while (left < right) {
while (left < right && !v[s[left]]) left++;
while (left < right && !v[s[right]]) right--;
swap(s[left], s[right]);
left++; right--;
}
return s;
}
};