leetcode-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:

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

Example 2:

Given s = “leetcode”, return “leotcede”.

分析


建立一个元音的哈希表,一前一后两指针向中间推进,每推进一次交换一次。

解决方案1(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
string reverseVowels(string s) {
bool hash_table[128] = {false};
hash_table['a'] = true, hash_table['e'] = true, hash_table['i'] = true, hash_table['o'] = true, hash_table['u'] = true;
hash_table['A'] = true, hash_table['E'] = true, hash_table['I'] = true, hash_table['O'] = true, hash_table['U'] = true;
int len = s.size();
int left = 0;
int right = len - 1;
string res = s;

if(len < 2) {
return res;
}

while(left < right) {
while(!hash_table[res[left]]) {
left++;
}
while(!hash_table[res[right]]) {
right--;
}
if(left < right) {
swap(res[left], res[right]);
}
left++;
right--;
}
return res;
}
};

相关问题


(E) Reverse String

题目来源