https://leetcode.com/problems/reverse-vowels-of-a-string/description/
Solution 1. Use array as a map.
string reverseVowels(string s) {
vector<int> mp('z'+1, 0);
mp['a'] = 1, mp['A'] = 1;
mp['e'] = 1, mp['E'] = 1;
mp['i'] = 1, mp['I'] = 1;
mp['o'] = 1, mp['O'] = 1;
mp['u'] = 1, mp['U'] = 1;
for(int i=0, j=s.size()-1; i<j;) {
if(mp[s[i]] && mp[s[j]]) {
swap(s[i], s[j]);
i++;
j--;
continue;
}
if(!mp[s[i]]) i++;
if(!mp[s[j]]) j--;
}
return s;
}
Solution 2. Use a map.
string reverseVowels(string s) {
unordered_map<char, int> mp = {{'a', 1}, {'e',1}, {'i',1},{'o',1},{'u',1}
,{'A', 1}, {'E',1}, {'I',1},{'O',1},{'U',1}};
for(int i=0, j=s.size()-1; i<j;) {
if(mp.count(s[i]) && mp.count(s[j])) {
swap(s[i], s[j]);
i++;
j--;
}
if(!mp.count(s[i])) i++;
if(!mp.count(s[j])) j--;
}
return s;
}
No comments:
Post a Comment