Write a function that takes a string as input and reverse only the vowels of a string.
样例
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "lintcode", return "lentcodi".
解题思路:
对撞指针。使用哈希表存储元音字母,注意大写也算!指针i,j分别指向左边的元音字母与右边的元音字母。
class Solution {
public:
/**
* @param s: a string
* @return: reverse only the vowels of a string
*/
string reverseVowels(string &s)
{
// write your code here
int i = 0;
int j = s.size()-1;
unordered_set<char> vowels{'a','e','i','o','u','A','E','I','O','U'};
string res = s;
while(i<j)
{
if(vowels.count(res[i])&&vowels.count(res[j]))
swap(res[i++],res[j--]);
else if(vowels.count(res[i])==0)
i++;
if(vowels.count(res[j])==0)
j--;
}
return res;
}
};