Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
Given s = "leetcode", return "leotcede".
Note:
The vowels does not include the letter "y".
The vowels does not include the letter "y".
[Thoughts]
双指针扫描。一个从头部,一个从尾部,发现vowel就swap。
[Code]
1: string reverseVowels(string s) {
2: set<char> vowels{'a', 'o', 'e', 'i', 'u', 'A', 'O', 'E', 'I', 'U'};
3:
4: for(int i =0, j = s.size()-1; i< j; ) {
5: if(vowels.find(s[i]) == vowels.end()) {
6: i++;
7: continue;
8: }
9:
10: if(vowels.find(s[j]) == vowels.end()) {
11: j--;
12: continue;
13: }
14:
15: swap(s[i], s[j]);
16: i++;
17: j--;
18: }
19:
20: return s;
21: }
No comments:
Post a Comment