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

 1 class Solution {
 2 public:
 3     string reverseVowels(string s) {
 4        vector<char> vet{'A','E','I','O','U', 'a', 'e', 'i', 'o', 'u' };
 5         int len = s.size();
 6         int first = 0;
 7         int last = len - 1;
 8         cout << first << " " << last << endl;
 9         cout << vet.size() << endl;
10         while (first <= last)
11         {
12             int i,j;
13             for (i = 0; i < vet.size(); i++)
14             {
15                 if (s[first] == vet[i])
16                     break;
17             }
18             if (i>=vet.size())
19             {
20                 first++;
21             }
22             for (j = 0; j < vet.size(); j++)
23             {
24                 if (s[last] == vet[j])
25                     break;
26             }
27             if (j >= vet.size())
28             {
29                 last--;
30             }
31             if (i < vet.size() && j < vet.size())
32             {
33                 swap(s[first], s[last]);
34                 first++;
35                 last--;
36             }
37         }
38         return s;
39     }
40 };

别人的代码是下面的:

 1 class Solution {
 2 public:
 3     string reverseVowels(string s) {
 4         int i = 0, j = s.size();
 5         string s1 = "aAeEiIoOuU";
 6         
 7         while( i < j ) {
 8             if ( s1.find_first_of(s[i]) == std::string::npos ) {
 9                 i++;
10                 continue;
11             }
12             
13             if ( s1.find_first_of(s[j]) == std::string::npos ) {
14                 j--;
15                 continue;
16             }
17             
18             swap(s[i], s[j]);
19             i++;
20             j--;
21         }
22         
23         return s;
24     }
25 };

 

posted on 2017-06-13 09:26  无惧风云  阅读(114)  评论(0编辑  收藏  举报