题目:
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".
题意:
给一个字符串,要求只把其中的元音字母的顺序反转,而保持辅音字母顺序不变。
将字符串s中所有的元音字母提取出来,单独翻转后,再将只含元音字母的字符串替换进源字符串去。
另一种思路是设置两个指针,分别从首尾开始循环找元音字母,找到后交换两个字母的位置,直到循环结束,实现反转。
代码如下:
第一种思路:
class Solution {
public:
bool isVowel(char c) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
return true;
if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
return true;
return false;
}
string reverseVowels(string s) {
string a;
for (char c : s) {
if (isVowel(c)) {
a.push_back(c);
}
}
reverse(a.begin(), a.end());
for (int i = 0, j = 0; i < s.length(); i ++) {
if (isVowel(s[i])) {
s[i] = a[j++];
}
}
return s;
}
};
第二种思路:
class Solution {
public:
bool isVowel(char c) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
return true;
if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
return true;
return false;
}
string reverseVowels(string s) {
int l = 0, r = s.length()-1;
while (l < r && !isVowel(s[l])) l++;
while (l < r && !isVowel(s[r])) r--;
while (l < r) {
swap(s[l++], s[r--]);
while (l < r && !isVowel(s[l])) l++;
while (l < r && !isVowel(s[r])) r--;
}
return s;
}
};