题目
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例1
输入:“hello”
输出:“holle”
示例2
输入:“leetcode”
输出:“leotcede”
题解
将元音字母的大小写放在set中,类比二分法
class Solution {
public:
string reverseVowels(string s) {
int left = 0;
int right = s.size()-1;
set<char> dic{'a','e','i','o','u','A','E','I','O','U'};
while(left<right)
{
if(dic.find(s[left]) == dic.end()) { //或者使用 !dic.count(s[left])
left++;
} else if(dic.find(s[right]) == dic.end()) {
right--;
} else {
swap(s[left], s[right]);
left++;
right--;
}
}
return s;
}
};