# 345. Reverse Vowels of a String 反转字符串中的元音字母

@TOC

[LeetCode]

Total Accepted: 7758 Total Submissions: 22132 Difficulty: Easy

## # 题目描述

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".

## # 解题方法

### # 使用栈

``````class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
vstack = []
for c in s:
if c in "aeiouAEIOU":
vstack.append(c)
res = []
for c in s:
if c in "aeiouAEIOU":
res.append(vstack.pop())
else:
res.append(c)
return "".join(res)
``````

### # 双指针

python代码如下：

``````class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
N = len(s)
res = list(s)
left, right = 0, N - 1
while left < right:
while right >= 0 and res[right] not in "aeiouAEIOU":
right -= 1
while left < right and res[left] not in "aeiouAEIOU":
left += 1
if left < right:
res[left], res[right] = res[right], res[left]
left += 1
right -= 1
return "".join(res)
``````

Java代码如下：

``````public class Solution {
public String reverseVowels(String s) {
ArrayList<Character> list=new ArrayList();

char[] array=s.toCharArray();

int tail=array.length-1;

continue;
}
if(!list.contains(array[tail])){
tail--;
continue;
}
array[tail]=temp;

tail--;
}

return new String(array);
}
}
``````

AC:11ms

C++代码如下：

``````class Solution {
public:
string reverseVowels(string s) {
const int N = s.size();
int left = 0, right = N - 1;
while (left < right) {
while (left < N && !isVowel(s[left])) left ++;
while (right >= 0 && !isVowel(s[right])) right --;
if (left < right)
swap(s[left], s[right]);
left ++;
right --;
}
return s;
}
private:
bool isVowel(char x) {
string t = "aeiouAEIOU";
return t.find(x) != string::npos;
}
};
``````

## # 日期

2016/5/1 20:52:19 2018 年 11 月 21 日 —— 又是一个美好的开始 2018 年 12 月 4 日 —— 周二啦！