题目描述:
标签:双指针 字符串
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
代码:
思路分析:
1、因为要判断是否是元音字母,所以定义一个set,用set.contains()方法来判断是不是元音字母,这里学会了一种简单创建set的方法,new HashSet<>(List),这样就不用一个个set.add()了。
2、定义双指针,left = 0 和 right = s.length() - 1
3、构建一个字符数组存放结果
4、当左/右指针指向的元素不是元音字母时,直接保存结果ans[left++]=ci,ans[right--]=cj;否则交换保存ans[left++]=cj,ans[right--]=ci。
5、最后掌握一个用字符数据直接new String(char[])的方法
class Solution {
public String reverseVowels(String s) {
Set<Character> set = new HashSet<>(Arrays.asList('a','e','i','o','u','A','E','I','O','U'));
int left = 0;
int right = s.length() - 1;
char[] ans = new char[s.length()];
while(left <= right){
char ci = s.charAt(left);
char cj = s.charAt(right);
if(!set.contains(ci)){
ans[left++] = ci;
}else if(!set.contains(cj)){
ans[right--] = cj;
}else{
ans[left++] = cj;
ans[right--] = ci;
}
}
return new String(ans);
}
}