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;
}
};