345. Reverse Vowels of a String【easy】
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:
bool isVowels(char x)
{
if (x >= 'A' && x <= 'Z') {
x += ;
}
return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u');
} void reverseChar(string &s, int start, int end)
{
char temp = s[start];
s[start] = s[end];
s[end] = temp;
} string reverseVowels(string s) {
int start = ;
int end = s.length() - ; while (start < end) {
while (start < end && !isVowels(s[start])) {
++start;
} while (start < end && !isVowels(s[end])) {
--end;
} reverseChar(s, start, end);
++start;
--end;
} return s;
}
};
注意循环的条件
解法二:
class Solution {
public:
string reverseVowels(string s) {
int i = , j = s.size() - ;
while (i < j) {
i = s.find_first_of("aeiouAEIOU", i);
j = s.find_last_of("aeiouAEIOU", j);
if (i < j) {
swap(s[i++], s[j--]);
}
}
return s;
}
};
参考@tedbear 的代码。