标签:tco ret ted int clu 注意 first hello amp
345. Reverse Vowels of a String【easy】
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 bool isVowels(char x) 4 { 5 if (x >= ‘A‘ && x <= ‘Z‘) { 6 x += 32; 7 } 8 return (x == ‘a‘ || x == ‘e‘ || x == ‘i‘ || x == ‘o‘ || x == ‘u‘); 9 } 10 11 void reverseChar(string &s, int start, int end) 12 { 13 char temp = s[start]; 14 s[start] = s[end]; 15 s[end] = temp; 16 } 17 18 string reverseVowels(string s) { 19 int start = 0; 20 int end = s.length() - 1; 21 22 while (start < end) { 23 while (start < end && !isVowels(s[start])) { 24 ++start; 25 } 26 27 while (start < end && !isVowels(s[end])) { 28 --end; 29 } 30 31 reverseChar(s, start, end); 32 ++start; 33 --end; 34 } 35 36 return s; 37 } 38 };
注意循环的条件
1 class Solution { 2 public: 3 string reverseVowels(string s) { 4 int i = 0, j = s.size() - 1; 5 while (i < j) { 6 i = s.find_first_of("aeiouAEIOU", i); 7 j = s.find_last_of("aeiouAEIOU", j); 8 if (i < j) { 9 swap(s[i++], s[j--]); 10 } 11 } 12 return s; 13 } 14 };
参考@tedbear 的代码。
345. Reverse Vowels of a String【easy】
标签:tco ret ted int clu 注意 first hello amp
原文地址:http://www.cnblogs.com/abc-begin/p/7583477.html