1.10 Reverse Vowels of String
Description
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".
Method
two pointer
Time and Space Complexity
o(n)
Code
public class Solution {
public String reverseVowels(String s) {
if (s == null || s.length() <= 1){
return s;
}
char[] strs = s.toCharArray();
int l = 0;
int r = s.length() - 1;
while (l < r){
while (l < r && !isVowel(strs[l])){
l++;
}
while (l < r && !isVowel(strs[r])){
r--;
}
char c = strs[l];
strs[l] = strs[r];
strs[r] = c;
l++;
r--;
}
return new String(strs);
}
private boolean isVowel(char s){
s = Character.toLowerCase(s);
if (s == 'a' || s == 'e' || s == 'i' || s == 'o' || s == 'u'){
return true;
}
return false;
}
}