Java solution beats 54%, what can be improved?


  • 0

    Two pointers solution. I see people put vowels in a string and use contains() to check if a character is vowel, not sure if it's a good practice.

    public class Solution {
        private static final Set<Character> vowels = new HashSet<Character>() {{
            add('a');
            add('e');
            add('i');
            add('o');
            add('u');
            add('A');
            add('E');
            add('I');
            add('O');
            add('U');
        }};
        public String reverseVowels(String s) {
            char [] str = s.toCharArray();
            int start = 0;
            int end = s.length() - 1;
            while(start < end) {
                while(start < s.length() && !vowels.contains(str[start])) {start++;}
                while((end >= 0) && (!vowels.contains(str[end]))) {end--;}
                if(start < end) {
                    char temp = str[start];
                    str[start++] = str[end];
                    str[end--] = temp;
                }
            }
            return String.valueOf(str);
        }
    }
    

Log in to reply
 

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