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".
This problem lets us flip the vowel in the string, the vowel letter has five a,e,i,o,u, need to pay attention to the uppercase also count, so there is a total of 10 letters. We write a Isvowel function to determine whether the current character is a vowel, if both sides are vowels, then we exchange, if the left is not, move one bit to the right, if not on the right, then move one bit to the left, see the code below:
Solution One:
classSolution { Public: stringReversevowels (strings) {intleft =0, right= s.size ()-1; while(Left <Right ) { if(Isvowel (S[left]) &&Isvowel (S[right])) {Swap (S[left+ +], s[right--]); } Else if(Isvowel (S[left])) {--Right ; } Else { ++Left ; } } returns; } BOOLIsvowel (Charc) {returnc = ='a'|| c = ='e'|| c = ='I'|| c = ='o'|| c = ='u'|| c = ='A'|| c = ='E'|| c = ='I'|| c = ='O'|| c = ='U'; }};
Or we can use our own function find_first_of and find_last_of to find the next position that contains any character in a given string:
Solution Two:
classSolution { Public: stringReversevowels (strings) {intleft =0, right = S.size ()-1; while(Left <Right ) { Left= S.find_first_of ("Aeiouaeiou", left); Right= S.find_last_of ("Aeiouaeiou", right); if(Left <Right ) {Swap (S[left+ +], s[right--]); } } returns; }};
We can also put a vowel letter in a string, and then each encounter a character, to the vowel string to find, if it exists to indicate that the current character is a vowel character, see the code is as follows:
Solution Three:
classSolution { Public: stringReversevowels (strings) {intleft =0, right = S.size ()-1; stringt ="Aeiouaeiou"; while(Left <Right ) { if(T.find (s[left]) = =string:: NPOs) + +Left ; Else if(T.find (s[right]) = =string:: NPOs)--Right ; ElseSwap (s[left++], s[right--]); } returns; }};
Similar topics:
Reverse String
Reverse Words in a String II
Reverse Words in a String
Resources:
Https://leetcode.com/discuss/99048/easy-to-understand-c-solution
Https://leetcode.com/discuss/99047/super-clean-solution-using-find_first_of-and-find_last_of
Https://leetcode.com/discuss/99062/java-two-pointers-solution-easy-understand-finish-interview
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Reverse vowels of a string flips the vowel letters in a string