https://leetcode.com/problems/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".两个指针,查找交换字符。一开始忘记在SWAP之后,移动指针了,导致死循环。。。新学到一个string::npos indicates no matches。
1 #include2 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 case18 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 }
string::find - C++ Reference
http://www.cplusplus.com/reference/string/string/find/
string::npos - C++ Reference
http://www.cplusplus.com/reference/string/string/npos/