题目:
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));
}
}
博客给出一道LeetCode题目,要求编写函数反转字符串中的元音字母,给出示例及注意事项,元音不包含字母 'y',并指出使用对撞指针解决该问题。
445

被折叠的 条评论
为什么被折叠?



