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. 思路
- 找出所有的元音字母,保存下來,並將其替換成’*’
- 利用保存下來的元音字符串,對原字符串中的’*’進行逆序替換
3. 算法
class Solution {
public:
string reverseVowels(string s) {
string vowels;
auto pos = s.find_first_of("aAeEiIoOuU");
while (pos != string::npos) {
vowels += s[pos];
s[pos] = '*';
pos = s.find_first_of("aAeEiIoOuU", pos + 1);
}
for (int i = vowels.size() - 1, j = 0; i >= 0 && j < s.size(); --i) {
while (s[j] != '*') ++j;
s[j] = vowels[i];
}
return s;
}
};