[LeetCode]345. Reverse Vowels of a String

Problem

Write a function that takes a string as input and reverse only the vowels of a string.

1
2
3
4
5
6
7
8
Example 1:

Input: "hello"
Output: "holle"
Example 2:

Input: "leetcode"
Output: "leotcede"

Note: The vowels does not include the letter “y”.

Solution

Analysis

翻转字符串中的元音字母. 首先,我们需要记录元音字母都有哪些, 然后双指针遍历字符串,判断当前字符是否属于元音字母,找到之后交换位置,继续遍历.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
string reverseVowels(string s) {
set<char> vowels{'a','e','i','o','u', 'A','E','I', 'O','U'};
int size = s.size(), l = 0, r = size - 1;

while (l < r){
while (l < size && vowels.count(s[l]) == 0) l++;
while (r > l && vowels.count(s[r]) == 0) r--;

if (l >= size || r <= l)
break;
else{
swap(s[l++], s[r--]);
}
}
return s;
}
};
您的支持就是我更新的最大动力!谢谢!