题意:给定一个字符串,反转字符串中的元音字母。
例如:
Input: "leetcode"
Output: "leotcede"
法一:双指针
class Solution {
public:
string reverseVowels(string s) {
if(s == "") return "";
set <char> st ={'a','e','i','o','u','A','E','I','O','U'};
int head = 0;
int tail = s.size() - 1;
char ans[10000000] = {};
while(head <= tail){
char h = s[head];
char t = s[tail];
if(st.find(h) == st.end()){
ans[head++] = h;
}
else if(st.find(t) == st.end()){
ans[tail--] = t;
}
else{
ans[head++] = t;
ans[tail--] = h;
}
}
return string(ans);
}
};
法二:首先将字符串中所有元音字母按顺序记录在v中,然后逆序遍历字符串,将v中的元音字母依次替换到逆序遍历过程中遍历到的元音字母中即可。
class Solution {
public:
string reverseVowels(string s) {
if(s == "") return "";
set <char> st ={'a','e','i','o','u','A','E','I','O','U'};
vector<char> v;
int len = s.size();
for(int i = 0; i < len; ++i){
if(st.find(s[i]) != st.end()){
v.push_back(s[i]);
}
}
int vowel_len = v.size();
for(int i = len - 1, j = 0; i >= 0 && j < vowel_len; --i){
if(st.find(s[i]) != st.end()){
s[i] = v[j++];
}
}
return s;
}
};