345. Reverse Vowels of a Stringeasy
Posted abc_begin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了345. Reverse Vowels of a Stringeasy相关的知识,希望对你有一定的参考价值。
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 Stringeasy的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 345. Reverse Vowels of a String
LeetCode #345 Reverse Vowels of a String
[LeetCode]345 Reverse Vowels of a String
345. Reverse Vowels of a Stringeasy