0%

reverse-vowels-of-a-string

Reverse Vowels of a String – LeetCode 345

Problem

Description

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

Example

Given s = “hello”, return “holle”.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
string reverseVowels(string s) {
int left = 0, right = s.size() - 1;
while (left < right) {
left = s.find_first_of("aeiouAEIOU", left);
right = s.find_last_of("aeiouAEIOU", right);
if (left < right) {
swap(s[left++], s[right--]);
}
}
return s;
}
};

思路

前后两端寻找,一旦找到就进行交换。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$12$ ms,排名$77.79\%$

Better

思路

还没看到更好的思路。