问题描述:
Write a function that takes a string as input and reverse only the vowels of a string.
示例:
Given s = "hello", return "holle".
Given s = "leetcode", return "leotcede".
问题分析:
我们使用双指针,一个向后移动,一个向前移动,一旦找到符合要求的元音字母,就交换两者的值,直到两个指针指到同一个位置。
过程详见代码:
class Solution {
public:
string reverseVowels(string s) {
int i = 0;
int j = s.length() - 1;
while(i < j)
{
if(!isVowels(s[i])) i++;
else if(!isVowels(s[j])) j--;
else
{
swap(s[i], s[j]);
i++;
j--;
}
}
return s;
}
bool isVowels(char c)
{
c = tolower(c);
return c == 'a' || c == 'o' || c == 'e' || c == 'u' || c == 'i';
}
};