题目:
Given a string s
, reverse only all the vowels in the string and return it.
The vowels are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
, and they can appear in both cases.
Example 1:
Input: s = "hello" Output: "holle"
Example 2:
Input: s = "leetcode" Output: "leotcede"
Constraints:
1 <= s.length <= 3 * 105
s
consist of printable ASCII characters.
思路:
要交换位置,明显的双指针。先用哈希set记录下元音,可以只记录全大写或者全小写,在判断的时候多写一些语句也行,不过这里偷懒就把大小写元音都记录下来了。两个指针分别index = 0 和 n - 1,只要左指针的当前字母不在哈希set内,右移;同理右指针的当前字母不在哈希set内就左移,如果当前左指针index小于右指针index,则交换元素并且再次移动指针。最后返回字符串即可。
代码:
class Solution {
public:
string reverseVowels(string s) {
unordered_set<char> mp= {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
int n = s.size(), i = 0, j = n - 1;
while (i < j) {
while (i < n && !mp.count(s[i]))
i++;
while ( j > 0 && !mp.count(s[j]))
j--;
if (i < j) {
swap(s[i], s[j]);
i++;
j--;
}
}
return s;
}
};