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

Note:
The vowels does not include the letter "y".

 答案:

    用首尾两个指针遍历,若两个都为元音,则交换,判断是否为元音可用一个set集合实现,看待判字符是否在set中。

 1 class Solution {
 2 public:
 3     string reverseVowels(string s) {
 4         if(s.length()==0){
 5             return s;
 6         }
 7         int i=0,j=s.length()-1;
 8         while(i<j){
 9             if(isvowel(s[i])&&isvowel(s[j])){
10                 swap(s[i],s[j]);
11                 i++;
12                 j--;
13             }
14             else if(isvowel(s[i])&&(!isvowel(s[j]))){
15                 j--;
16             }
17             else if(isvowel(s[j])&&(!isvowel(s[i]))){
18                 i++;
19             }
20             else{
21                 i++;
22                 j--;
23             }
24         }
25         return s;
26     }
27     bool isvowel(char ch){
28          set<char>vowels{'a','e','i','o','u','A','E','I','O','U'};
29          if(vowels.count(ch)!=0){
30              return true;
31          }
32          else{
33              return false;
34          }
35     }
36 };

 

posted @ 2016-08-02 13:49  绵绵思远道  阅读(128)  评论(0编辑  收藏  举报