I am trying to reverse the vowels of a String. My program works but it is slow and times out on large Strings. How could I make it faster? Write a function that takes a string as input and reverse only the vowels of a string.
Example 1: Given s = "hello"
, return "holle"
.
Example 2: Given s = "leetcode"
, return "leotcede"
.
Note: The vowels does not include the letter "y".
public class Solution {
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;
}
}
Edit: I have changed my code to use StringBuilder and now it passes the test cases but it is still slower than 95% of Java solutions, so I will make the other changes to try to make it faster. The slowness in my program is not entirely due to not using StringBuilder. Even with that change, my program is still very slow. It's not a duplicate of other questions.