2021-03-28 LeetCode刷题 --345 反转字符串中的元音字母
题目描述:编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
下面是我写的:
class Solution {
public String reverseVowels(String s) {
char[] a=s.toCharArray();
char c='a';
HashSet<Character> yuan= new HashSet<>(
Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
int low=0;
int high =a.length-1;
while(low<=high){
while(low<=a.length-1&&!yuan.contains(a[low])){
low++;
}
while(high>=0&&!yuan.contains(a[high])){
high--;
}
if(low<=high){
c=a[low];
a[low++]=a[high];
a[high--]=c;
}else{
break;
}
}
s=String.valueOf(a) ;
return s;
}
}
缺点:刚开始只会用ArrayList来建造集合,然后一个个的add进去,集合还不了解;
用的是字符串和字符数组的转换;
while里面的东西出错了好多次;
大神写的:
private final static HashSet<Character> vowels = new HashSet<>(
Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
public String reverseVowels(String s) {
if (s == null) return null;
int i = 0, j = s.length() - 1;
char[] result = new char[s.length()];
while (i <= j) {
char ci = s.charAt(i);
char cj = s.charAt(j);
if (!vowels.contains(ci)) {
result[i++] = ci;
} else if (!vowels.contains(cj)) {
result[j--] = cj;
} else {
result[i++] = cj;
result[j--] = ci;
}
}
return new String(result);
}
有点:利用好了很多String的方法,如charAt();