345. Reverse Vowels of a String (Easy)
https://leetcode.com/problems/reverse-vowels-of-a-string/
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello" Output: "holle"
Example 2:
Input: "leetcode" Output: "leotcede"
Note:
The vowels does not include the letter "y".
Solutions
class Solution {
private boolean isVowel(char c) {
List<Character> vowels = Arrays.asList(new Character[]{'a', 'e', 'i', 'o', 'u'});
if (vowels.contains(String.valueOf(c).toLowerCase().charAt(0))) {
return true;
}
return false;
}
private void swap(char[] cs, int x, int y) {
char tmp = cs[x];
cs[x] = cs[y];
cs[y] = tmp;
}
public String reverseVowels(String s) {
if (s == null || s.length() == 0) {
return "";
}
int len = s.length();
char[] chars = s.toCharArray();
int left = 0;
int right = len - 1;
while(left < right) {
while (left < len && !isVowel(s.charAt(left))) {
left++;
}
while (right > 0 && !isVowel(s.charAt(right))) {
right--;
}
if (left >= right) {
break;
}
swap(chars, left, right);
left++;
right--;
}
String ans = "";
for (int i = 0; i < len; i++) {
ans += chars[i];
}
return ans;
}
}