
private final static HashSet<Character> vowel = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
public String reverseVowels(String s) {
int start = 0;
int end = s.length() - 1;
char[] res = new char[s.length()];
while (start<=end){
char sc = s.charAt(start);
char ec = s.charAt(end);
if(!vowel.contains(sc))
res[start++] = sc;
else if (!vowel.contains(ec))
res[end--] = ec;
else {
res[start++] = ec;
res[end--] = sc;
}
}
return new String(res);
}
本文介绍了一种使用Java实现的算法,该算法可以反转字符串中的所有元音字母位置,同时保持辅音字母的位置不变。通过使用HashSet来存储元音字母,并采用双指针技术,此算法在O(n)的时间复杂度内完成任务。
1215

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



