One pass Java Solution 13ms


  • 19
    H
    public class Solution {
        public String reverseVowels(String s) {
            char[] list=s.toCharArray();
            Set<Character> set=new HashSet<>();
            set.add('a');
            set.add('e');
            set.add('i');
            set.add('o');
            set.add('u');
            set.add('A');
            set.add('E');
            set.add('I');
            set.add('O');
            set.add('U');
            for (int i=0, j=list.length-1; i<j; ) {
                if (!set.contains(list[i])) {
                    i++;
                    continue;
                }
                if (!set.contains(list[j])) {
                    j--;
                    continue;
                }
                char temp=list[i];
                list[i]=list[j];
                list[j]=temp;
                i++;
                j--;
            }
            return String.valueOf(list);
        }
    }
    

    We could also initilize the set like this:

    Set<Character> vowels = new HashSet<>(Arrays.asList(new Character[]{'a','e','i','o','u','A','E','I','O','U'}));
    

  • 10
    G

    Hi, set can be initialized like this:

    Set<Character> vowels = new HashSet<>(Arrays.asList(new Character[]{'a','e','i','o','u','A','E','I','O','U'}));
    

  • 0
    H

    @guangstick yes, you r right


  • 0
    Y

    Hi @guangstick actually the following also works

    Set<Character> set = new HashSet<Character>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
    

  • 0
    G

    @guangstick I just wonder why you don't use List,it also has the contains()method:

     List<Character> dic=Arrays.asList('a','e','i','o','u','A','E','I','O','U');
    

  • 0
    F

    This is awesome man. Good job using the Set!

    Also @Gene20 he uses a Set because the List Contains method takes O(n) time versus the Sets contains method taking O(1).

    Stack Overflow reference: https://stackoverflow.com/questions/32552307/hashset-vs-arraylist-contains-performance


  • 0
    S

    performance is not good, because each time even i or j already find a vowel, you still need to check set.contains(list[i]) or set.contains(list[j]) whether the other pointer is looking for a vowel.

    However sometimes performance and succinctness is a tradeoff.


Log in to reply
 

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