1.题目
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”.
给一个字符串,翻转其中的元音字母
2.分析
两个指针分别从头部和尾部开始往中间遍历。遇到元音字母则swap。
3.代码
class Solution {
public:
bool isVowel(char c) {
return c == 'A' || c == 'a' || c == 'E' || c == 'e' || c == 'I' || c == 'i' || c == 'O' || c == 'o' || c == 'U' || c == 'u';
}
string reverseVowels(string s) {
int i = 0;
int j = s.size() - 1;
while (i < j) {
if (isVowel(s[i]) && isVowel(s[j])) {
swap(s[i], s[j]);
++i;
--j;
}
else if (!isVowel(s[i]))
++i;
else if (!isVowel(s[j]))
--j;
}
return s;
}
};