码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 345. Reverse Vowels of a String

时间:2016-05-20 06:13:30      阅读:298      评论:0      收藏:0      [点我收藏+]

标签:

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

两个指针,查找交换字符。一开始忘记在SWAP之后,移动指针了,导致死循环。。。新学到一个string::npos indicates no matches。

技术分享
 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Solution {
 5 public:
 6 /*
 7     bool isVowels(char chIn)
 8     {
 9         return ((toupper(chIn) == ‘A‘ || toupper(chIn) == ‘E‘ || toupper(chIn) == ‘I‘ || toupper(chIn) == ‘O‘ || toupper(chIn) == ‘U‘));
10     }
11 */
12     
13     string reverseVowels(string s) {
14         int i = 0, j = s.length() - 1;
15         string sVowels = "aeiouAEIOU";
16 
17         // Remember special case
18         if (s == "" || s.length() == 0) return s;
19         
20         while (i < j)
21         {
22 //            while (!isVowels(s[i]) && (i < j)) i ++;
23               while ((sVowels.find(s[i]) == string::npos) && (i < j)) i ++;
24 //            while (!isVowels(s[j]) && (i < j)) j --;
25               while ((sVowels.find(s[j]) == string::npos) && (i < j)) j --;  
26                         
27             if (i < j)
28                 swap(s[i], s[j]);
29             
30             i ++;
31             j --;
32         }
33 
34         return s;
35     }
36 };
37 
38 int main ()
39 {
40     Solution testSolution;
41     string result;
42     
43     result = testSolution.reverseVowels("hello");    
44     cout << result << endl;
45     
46     char ch;
47     cin >> ch;
48     
49     return 0;
50 }
View Code

string::find - C++ Reference

http://www.cplusplus.com/reference/string/string/find/

string::npos - C++ Reference

http://www.cplusplus.com/reference/string/string/npos/

 

LeetCode 345. Reverse Vowels of a String

标签:

原文地址:http://www.cnblogs.com/pegasus923/p/5510740.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!