345. Reverse Vowels of a String
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
</pre><pre name="code" class="java">public class Solution {
Set<Character> set=new HashSet<Character>();
{
set.add('a');
set.add('e');
set.add('i');
set.add('o');
set.add('u');
set.add('A');
set.add('E');
set.add('I');
set.add('O');
set.add('U');
}
//题意:前后遇到元音字母就进行调换
public String reverseVowels(String s) {
char[] a=s.toCharArray();
int i=0;
int j=s.length()-1;
while(true){
while(i<j && !set.contains(a[i])){
i++;
}
while(j>=0 && !set.contains(a[j])){
j--;
}
if(i<j){
char temp=a[j];
a[j]=a[i];
a[i]=temp;
i++;
j--;
}else{
break;
}
}
return new String(a);
}
}
本文介绍了一种算法,该算法接收一个字符串作为输入,并仅反转字符串中的元音字母。通过双指针技术实现了高效的反转操作,同时保持辅音字母的位置不变。提供了详细的Java代码实现。
573

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



