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:
Input: "hello" Output: "holle"
Example 2:
Input: "leetcode" Output: "leotcede"
Note: The vowels does not include the letter "y".
思路: 只翻转元音字母,就只用两个指针,首尾移动来翻转元音字母。
代码:
java:
class Solution {
public static boolean[] vowels = new boolean[256];
static{
vowels['a'] = true;
vowels['o'] = true;
vowels['e'] = true;
vowels['i'] = true;
vowels['u'] = true;
vowels['A'] = true;
vowels['O'] = true;
vowels['E'] = true;
vowels['I'] = true;
vowels['U'] = true;
}
public String reverseVowels(String s) {
if(s == null || s.isEmpty()) return "";
int i = 0, j = s.length() - 1;
char[] str = s.toCharArray();
while(i < j) {
while(i < j && !vowels[str[i]]) i++;
while(i < j && !vowels[str[j]]) j--;
if(i < j) {
char temp = str[i];
str[i++] = str[j];
str[j--] = temp;
}
}
return String.valueOf(str);
}
}