反转字符串中的元音字母
难度:简单
利用双指针扫描,当左右指针都是元音字母时,进行互换并移到下一位
这里借鉴了下大神的写法,使用容器将元音字母存储,并使用 static 修饰,确保整个容器的创建和元音字母的填入在所有测试样例中只会发生一次。缩短了执行用时。
代码如下:
class Solution {
static char[] vowels = new char[]{'a','e','i','o','u'};
static Set<Character> set = new HashSet<>();
static{
for (char c : vowels) {
set.add(c);
set.add(Character.toUpperCase(c));
}
}
public String reverseVowels(String s) {
char[] cs = s.toCharArray();
int pre = 0;
int end = s.length()-1;
while(pre<end){
if (!set.contains(cs[pre])){
pre++;
continue;
}
if (!set.contains(cs[end])){
end--;
continue;
}
char temp = cs[pre];
cs[pre] = cs[end];
cs[end] = temp;
pre++;
end--;
}
return String.valueOf(cs);
}
}
执行结果:通过