LeetCode Problem
345. Reverse Vowels of a String
Link to LeetCode
Given a string s, reverse only all the vowels in the string and return it.
The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.
Input: s = "IceCreAm"
Output: "AceCreIm"
Explanation: The vowels in s are ['I', 'e', 'e', 'A']. On reversing the vowels, s becomes "AceCreIm".
class Solution {
Set< Character> vowels = new HashSet<>();
{
vowels.add('a');vowels.add('e');vowels.add('i');vowels.add('o');vowels.add('u');
vowels.add('A');vowels.add('E');vowels.add('I');vowels.add('O');vowels.add('U');
}
public String reverseVowels(String s) {
if(s == null || s.length() == 0) {
return s;
}
StringBuilder sb = new StringBuilder(s);
int start = 0, end = s.length()-1;
while (start < end) {
while (start < end && !vowels.contains(sb.charAt(start))) {
start++;
}
while (start < end && !vowels.contains(sb.charAt(end))) {
end--;
}
char ch = sb.charAt(start);
sb.setCharAt(start, sb.charAt(end));
sb.setCharAt(end, ch);
start++;
end--;
}
return sb.toString();
}
}