345. Reverse Vowels of a String

时间:2022-07-05 12:15:20

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".

代码如下:

 public class Solution {
public String reverseVowels(String s) {
ArrayList<Character> list=new ArrayList<>();
char[] ss=s.toCharArray();
list.add('a');
list.add('e');
list.add('i');
list.add('o');
list.add('u');
list.add('A');
list.add('E');
list.add('I');
list.add('O');
list.add('U');
int i=0,j=s.length()-1;
while(i<j)
{
while(!list.contains(ss[i])&&i<j)
i++;
while(!list.contains(ss[j])&&i<j)
j--; char c=ss[i];
ss[i]=ss[j];
ss[j]=c; i++;j--;
}
s=String.valueOf(ss);
return s;
}
}