345. Reverse Vowels of a String
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".
Solution
(1) Java
class Solution {
public String reverseVowels(String s) {
Set<Character> vowels = new HashSet<>(Arrays.asList('a','o','u','e','i', 'A','O','U','E','I'));
int i = 0;
int j = s.length()-1;
StringBuilder sb = new StringBuilder(s);
while (i < j) {
while (i < j && !vowels.contains(s.charAt(i))) {
i++;
}
while (j > i && !vowels.contains(s.charAt(j))) {
j--;
}
if (i < j) {
char c1= s.charAt(i);
char c2= s.charAt(j);
sb.setCharAt(i, c2);
sb.setCharAt(j, c1);
i++;
j--;
}
}
return sb.toString();
}
}
(2) Python
(3) Scala