1.题目
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例:
输入:"hello"输出:"holle"输入:"leetcode"输出:"leotcede"
提示:
- 元音字母不包含字母 “y” 。
2.思路
首先我们需要知道元音字母包括哪几个,26个英文字母中有5个元音字母与21个辅音字母构成,五个元音字母分别是:a、e、i、o、u
双指针解法:
public String reverseVowels(String s) {// 对撞指针解法// 区分大小写if(s == null || s.length() < 2) return s;char[] chars = s.toCharArray();int i = 0, j = chars.length - 1;while (i < j) {// 从前向后找到元音while(i < chars.length && !isVowel(chars[i]))i++;// 从后向前找到元音while(j >= 0 && !isVowel(chars[j]))j--;if (i < j) {// 进行元音反转char temp = chars[i];chars[i] = chars[j];chars[j] = temp;i++;j--;}}return String.valueOf(chars);}// 判断一个字符是否是元音字母public boolean isVowel(char c) {return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'|| c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' ;}
