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);
}
}