My algorithm is too slow to pass


  • 0
    S

    Could anyone give me some times on how to make my algorithm faster because it times out on large strings.

        public String reverseVowels(String s){
    
            Set<Character> vowel = new HashSet<>();
    
            char [] sArray = s.toCharArray();
            vowel.add('a');
            vowel.add('e');
            vowel.add('o');
            vowel.add('i');
            vowel.add('u');
            vowel.add('A');
            vowel.add('E');
            vowel.add('I');
            vowel.add('O');
            vowel.add('U');
    
            Stack<Character> v = new Stack<>();
            String temp = "";
    
            int i = 0;
            for (Character c: sArray){
                if (vowel.contains(c)){
                    v.push(c);
    
                }
                i++;
            }
            for (Character c: sArray){
                if (vowel.contains(c)){
                   if (!v.empty())
                    c = v.pop();
                }
                temp+= c;
    
            }
            return temp;
    
        }
    }```

Log in to reply
 

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