LeetCode : 345. Reverse Vowels of a String

 

这个题目本身很简单,主要是性能的问题,用string自带的函数find_first_of 和find_last_of,运行了72ms

 1 class Solution {
 2 public:
 3     string reverseVowels(string s) {
 4         string temp(s);
 5         bool loop = true;
 6         std::size_t posS = std::string::npos;
 7         std::size_t posE = std::string::npos;
 8         int offset=0;
 9 
10         while(loop){
11             posS = temp.find_first_of("aeiouAEIOU");
12             posE = temp.find_last_of("aeiouAEIOU");
13             if(posS<posE){
14                 char tempC = s[posS+offset];
15                 s[posS+offset] = s[posE+offset];
16                 s[posE+offset] = tempC;
17                 offset = offset + posS + 1;
18                 temp = temp.substr(posS+1,posE-posS-1);
19             }else{
20                 loop = false;
21             }
22         }
23         return s;
24     }
25 };

用处理数组的方式从两边向中间找用了20ms.

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

 

posted @ 2016-04-29 11:22  盛小胖  阅读(170)  评论(0编辑  收藏  举报