题目来源
反转元音字母,我一开始想了想,记录下所有元音字母的位置,然后再反转。代码如下:
class Solution {
public:
string reverseVowels(string s) {
int n = s.size();
vector<char> vowels{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
vector<int> pos;
for (int i=0; i<n; i++)
for (int j=0; j<vowels.size(); j++)
if (s[i] == vowels[j]) {
pos.push_back(i);
break;
}
string res(s);
int m = pos.size();
for (int i=0; i<m; i++) {
res[pos[i]] = s[pos[m-1-i]];
}
return res;
}
};
然后看了一下Tag,发现写着双指针,发现自己太傻逼了…
改了改,代码如下:
class Solution {
public:
string reverseVowels(string s) {
int n = s.size();
vector<char> vowels{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
int p1 = 0, p2 = n - 1;
string res(s);
while (p1 <= p2) {
bool left = false, right = false;
for (int i=0; i<vowels.size(); i++) {
if (res[p1] == vowels[i]) {
left = true;
}
if (res[p2] == vowels[i]) {
right = true;
}
}
if (left && right) {
iter_swap(res.begin()+p1, res.begin()+p2);
p1++;
p2--;
}
if (!left)
p1++;
if (!right)
p2--;
}
return res;
}
};
可以AC,但是自己写的代码有点乱有点长。然后看了下别人的,代码如下:
class Solution {
public:
string reverseVowels(string s) {
int dict[256] = {0};
dict['a'] = 1, dict['A'] = 1;
dict['e'] = 1, dict['E'] = 1;
dict['i'] = 1, dict['I'] = 1;
dict['o'] = 1, dict['O'] = 1;
dict['u'] = 1, dict['U'] = 1;
int start = 0, end = (int)s.size() - 1;
while(start < end){
while(start < end && dict[s[start]] == 0)
start++;
while(start < end && dict[s[end]] == 0)
end--;
swap(s[start], s[end]);
start++;
end--;
}
return s;
}
};