345. Reverse Vowels of a String
来源: LeetCode 345. Reverse Vowels of a String
题目描述
345. Reverse Vowels of a String
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello"
Output: "holle"
Example 2:
Input: "leetcode"
Output: "leotcede"
Note:
The vowels does not include the letter "y".
vowel 元音
思路分析
pair 记录位置取出所有元音,翻转他们
代码
class Solution {
#define SIZE(A) ((int)A.size())
#define LENGTH(A) ((int)A.length())
#define MP(A,B) make_pair(A,B)
#define PB(X) push_back(X)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,a) for(int i=0;i<(a);++i)
#define ALL(A) A.begin(),A.end()
using VI = vector<int>;
using VII = vector<VI>;
using VD = vector<double>;
typedef pair<char, int> PI;
using VP = vector<PI>;
public:
string reverseVowels(string s) {
VP arry;
char a[] = {'a','e','i','o','u','A','E','I','O','U'};
unordered_set<int> st(a, a+10); // 初始化集合
REP(i,SIZE(s)){
if(st.find(s[i]) != st.end()){
arry.PB(MP(s[i],i));
}
}
int i = 0, j = arry.size() - 1;
while(i<j){
char c = arry[i].first;
arry[i].first = arry[j].first;
arry[j].first = c;
++i;
--j;
} // 旋转
for(auto a:arry){
s[a.second] = a.first;
}
return s;
}
};
算法分析
- 时间复杂度:O(n)
- 空间复杂度:O(1)
代码改进
双指针跟踪