題目:
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;
}
};