题目链接: https://leetcode.com/problems/reverse-vowels-of-a-string/
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 = "leetcode", return "leotcede".
思路: 用一个hash表存一下元音字符, 然后设置左右指针找到两个都是元音的位置交换一下就可以了. 注意字符是大小写都有的.
代码如下:
class Solution {
public:
string reverseVowels(string s) {
if(s.length()==0) return "";
int left =0, right = s.length()-1;
set<char> hash{'a','e','i','o','u', 'A', 'E', 'I', 'O', 'U'};
while(left < right)
{
if(hash.count(s[left]) == 0)
left++;
if(hash.count(s[right]) == 0)
right--;
if(hash.count(s[left])!=0 && hash.count(s[right])!=0)
{
swap(s[left], s[right]);
left++, right--;
}
}
return s;
}
};