题目:
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".
Note:
The vowels does not include the letter "y".
思路:
还是一道热身题目。做这样的题目真爽!
代码:
class Solution {
public:
string reverseVowels(string s) {
unordered_set<char> hash = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
if (s.length() <= 1) {
return s;
}
int left = 0, right = s.length() - 1;
while (left < right) {
while (left < right && hash.count(s[left]) == 0) {
++left;
}
while (right > left && hash.count(s[right]) == 0) {
--right;
}
if (left < right) {
swap(s[left], s[right]);
++left, --right;
}
}
return s;
}
};