# LeetCode345. Reverse Vowels of a String（模拟）

## LeetCode345. Reverse Vowels of a String（模拟）

• Easy
• Accepted：139,692
• Submissions：343,552

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

### 链接

https://leetcode.com/problems/reverse-vowels-of-a-string/

### 题解

• 直接模拟就好了，使用对撞指针，时间复杂度为$O(n)$，注意一下大小写字母的判断。

### 代码

• Runtime: 8 ms, faster than 98.09% of C++ online submissions for Reverse Vowels of a String.
• Memory Usage: 1.3 MB, less than 28.79% of C++ online submissions for Reverse Vowels of a String.
class Solution {
public:
string reverseVowels(string s) {
set <char> st;
st.insert('a');
st.insert('e');
st.insert('i');
st.insert('o');
st.insert('u');
int l = 0, r = s.length() - 1;
while (l < r)
{
if (!st.count(s[l]) && !st.count(tolower(s[l])))
{
++l;
continue;
}
if (!st.count(s[r]) && !st.count(tolower(s[r])))
{
--r;
continue;
}
swap(s[l++], s[r--]);
}
return s;
}
};

The end.
2019年2月4日 星期一