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”.
This problem is solved using the most popular 2 pointers solution, which iterates the string from both sides. However, the trick is to store the vowels wisely, so that we can check if the current letter belongs to vowels or not.
My solution: store it in a set
class Solution {
public String reverseVowels(String s) {
int lo=0, hi=s.length()-1;
char [] ch = s.toCharArray();
Set<Character> set = new HashSet<>(Arrays.asList(new Character[]{'a','e','i','o','u','A','E','I','O','U'}));
while(lo<hi){
if(!set.contains(ch[lo])) lo++;
else if(!set.contains(ch[hi])) hi--;
else{
char tmp = ch[lo];
ch[lo]=ch[hi];
ch[hi]=tmp;
lo++;hi--;
}
}
return new String(ch);
}
}
Smarter way:
- Store the vowels in a string and check for String.contains() or String.indexOf():
(if indexOf returns -1 then not exist)
String.indexOf() is faster than contains(), because String.contains() is implemented by String.indexOf() in Java. - Store the vowels in a 256-sized boolean array: even faster retrieval.
public static boolean[] vowels = new boolean[256]; static{ vowels['a'] = true; vowels['o'] = true; vowels['e'] = true; vowels['i'] = true; vowels['u'] = true; vowels['A'] = true; vowels['O'] = true; vowels['E'] = true; vowels['I'] = true; vowels['U'] = true; }