This is the 11th day of my participation in Gwen Challenge
Reverse a vowel in a string
Topic describes
Write a function that takes a string as input and inverts the vowels in that string.
Example 1:
Input: “hello”
Output: “holle”
Example 2:
Input: “leetcode”
Output: “leotcede”
Tip:
- Vowels do not contain the letter “y”.
link
Leetcode.com/problems/re…
Thinking analytical
The first is to new a HashSet<Character> dedicated to 10 vowels. And an empty array result[] of the same length as the string, which is used to store the iterated element values.
Define two Pointers to one element and one to the next.
Make the following judgments once in each cycle:
- The current pointer to an element is a vowel. If the front pointer does not point to a vowel, it moves back one bit; If the back pointer does not point to a vowel, it moves forward one bit. Set the value of the current index to result.
- When both Pointers point to elements that are vowels, the index of the pointer is reversed and set to result.
At the end of the loop, the result is what we want.
Algorithm implementation
class Solution {
private final static HashSet<Character> vowelSet=new HashSet<>(
Arrays.asList('a'.'e'.'i'.'o'.'u'.'A'.'E'.'I'.'O'.'U'));public String reverseVowels(String s) {
if(s==null) {return s;
}
char[] result=new char[s.length()];
int i=0,j=s.length()-1;
while(i<=j){
char ci=s.charAt(i);
char cj=s.charAt(j);
if(! vowelSet.contains(ci)){ result[i++]=ci; }else if(! vowelSet.contains(cj)){ result[j--]=cj; }else{ result[i++]=cj; result[j--]=ci; }}return newString(result); }}Copy the code
Pattern design
There’s another charming way to do it. Using double Pointers in conjunction with the StringBuilder class is nice.
class Solution {
public String reverseVowels(String s) {
StringBuilder sb=new StringBuilder();
int j=s.length()-1;
for(int i=0; i<s.length(); i++){if("AEIOUaeiou".indexOf(s.charAt(i))! = -1) {while(j>=0&&"AEIOUaeiou".indexOf(s.charAt(j))==-1){
j--;
}
sb.append(s.charAt(j));
j--;
}else{ sb.append(s.charAt(i)); }}returnsb.toString(); }}Copy the code