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".
class Solution {
private boolean isVowel(String s, int i) {
String vowel = "aeiouAEIOU";
return vowel.contains(s.charAt(i) + "");
}
public String reverseVowels(String s) {
StringBuilder sb = new StringBuilder(s);
int l = 0, r = s.length() - 1;
while (l < r) {
if (!isVowel(s, l)) {
l++;
}
if (!isVowel(s, r)) {
r--;
}
if (isVowel(s, l) && isVowel(s, r)) {
sb.setCharAt(l, s.charAt(r));
sb.setCharAt(r, s.charAt(l));
l++;
r--;
}
}
return sb.toString();
}
}
时间复杂度O(n).