Java Solution with Set and Two Pointers


  • 0

    This solution has O(n) runtime with O(1) vowel lookup.

    public class Solution {
        public String reverseVowels(String s) {
            Character[] vowels = {'a','A','e','E','i','I','o','O','u','U'};
            Set<Character> myset = new HashSet<Character>();
            myset.addAll(Arrays.asList(vowels));
            char[] c = s.toCharArray();
            int p1=0;
            int p2=s.length()-1;
            while(p1 < p2){
                //both pointing to a vowel, then swap, then (in/de)crement
                if(myset.contains(c[p1]) && myset.contains(c[p2])){
                    char temp = c[p1];
                    c[p1] = c[p2];
                    c[p2] = temp;
                    p1++;p2--;
                } else if (myset.contains(c[p1])) {
                    //one pointing to a vowel, (in/de)crement the other
                    p2--;
                } else if (myset.contains(c[p2])) {
                    //one pointing to a vowel, (in/de)crement the other
                    p1++;
                } else {
                    p1++;
                    p2--;
                }
            }
            
            return String.valueOf(c);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.