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

思路: 用一个hash表存一下元音字符, 然后设置左右指针找到两个都是元音的位置交换一下就可以了. 注意字符是大小写都有的.

 1 class Solution {
 2 public:
 3     string reverseVowels(string s) {
 4         set<char> hash{'a', 'e', 'o', 'i', 'u','A', 'E', 'I', 'O', 'U'};
 5         int len = s.length();
 6         int left = 0, right = len - 1;
 7         while(left < right){
 8             if(hash.count(s[left]) == 0)
 9                 left++;
10             if(hash.count(s[right]) == 0)
11                 right--;
12             if(hash.count(s[left]) != 0 && hash.count(s[right]) != 0 ){
13                 swap(s[left], s[right]);
14                 left++;
15                 right--;
16             }
17         }
18         return s;
19         
20     }
21 };
View Code
原文地址:https://www.cnblogs.com/qinduanyinghua/p/5510079.html