欢迎转载,转载请注明:
http://blog.csdn.net/u013190088/article/details/67637260
Description
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”.
Note:
The vowels does not include the letter “y”.
解法:
把字符串里边的元音字母给调换顺序。可以先遍历字符串,记录元音所在下标到一个list,最后根据list中存储的下标信息替换位置即可。
public String reverseVolwels(String s) {
char[] ch = s.toCharArray();
List<Integer> list = new ArrayList<>();
String volwels = "aeiouAEIOU";
for(int i=0; i<ch.length; i++) {
if (volwels.contains(String.valueOf(ch[i]))) {
list.add(i);
}
}
for(int i=list.size()-1,j=0; j<i; i--,j++) {
int last = list.get(i);
int begin = list.get(j);
char tmp = ch[last];
ch[last] = ch[begin];
ch[begin] = tmp;
}
return String.valueOf(ch);
}