题目:
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".
本题使用对撞指针解决问题
public class ReverseVowels {
public static String reverseVowels(String s) {
if (null == s || "".equals(s))
return s;
int l = 0;
int r = s.length() - 1;
char[] charArray = s.toCharArray();
while (l <= r){
if (!isVowel(charArray[l])){
l++;
continue;
}
if (!isVowel(charArray[r])){
r--;
continue;
}
swap(charArray, l++, r--);
}
return String.valueOf(charArray);
}
public static boolean isVowel(char c){
char lowerCh = Character.toLowerCase(c);
if (lowerCh == 'a' || lowerCh == 'e' || lowerCh == 'i' || lowerCh == 'o' || lowerCh == 'u')
return true;
return false;
}
public static void swap(char[] charArray, int i, int j){
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
public static void main(String[] args) {
String s = "leetcode";
System.out.println(reverseVowels(s));
}
}