Thinking process

Upperclasses?

  • Yes

What are the patterns?

  • swap the current first and the last => two pointers

String is immutable!

  • StringBuilder or toCharArray()

Mistakes

TLE

  • l++ and r-- are important, otherwise vowels always has the current character

>>>>>

  • Don't need to use a hashSet. A simple String is enough
public class Solution {
    // private HashSet<Character> vowels = new HashSet<Character>(){
    //   {
    //       add('a');add('e');add('i');add('o');add('u');
    //   }  
    // };
    public String reverseVowels(String s) {
        if (s.length() <= 1) return s;
        StringBuilder sb = new StringBuilder(s);
        String vowels = "aAeEiIoOuU";
        int l = 0; 
        int r = s.length() - 1;

        while (l < r) {
            while (l < r && !vowels.contains(s.charAt(l)+"")) l++;
            while (l < r && !vowels.contains(s.charAt(r)+"")) r--;

            if (l < r && s.charAt(l) != s.charAt(r)) {
                char tmp = s.charAt(l);
                sb.setCharAt(l, s.charAt(r));
                sb.setCharAt(r, tmp);
            }

            l++;
            r--;

        }

        return sb.toString();
    }
}

The one using toCharArray()

public String reverseVowels(String s) {
    if(s == null || s.length()==0) return s;
    String vowels = "aeiouAEIOU";
    char[] chars = s.toCharArray();
    int start = 0;
    int end = s.length()-1;
    while(start<end){

        while(start<end && !vowels.contains(chars[start]+"")){
            start++;
        }

        while(start<end && !vowels.contains(chars[end]+"")){
            end--;
        }

        char temp = chars[start];
        chars[start] = chars[end];
        chars[end] = temp;

        start++;
        end--;
    }
    return new String(chars);
}

results matching ""

    No results matching ""