1.题目要求:
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".
Subscribe to see which companies asked this question
2.思路:
找出元音字母,倒序插入(要求的只是把元音的部分进行逆转,非元音的地方不进行逆转)
基本的思想就是:
①逆序单独找出元音字母
②顺序便利字符串,找到元音字母,依次进行替换
3.代码
public class Solution {
public String reverseVowels(String s) {
StringBuilder vowels=new StringBuilder();
String sl=s.toLowerCase();//toLowerCase的意思是将所有的英文字符转换为小写字母
//找出元音的出现的反顺序
for(int i=sl.length()-1;i>=0;i--) {
char tmp=sl.charAt(i);
if(tmp=='a' || tmp=='e' || tmp=='i' || tmp=='o' || tmp=='u'){
vowels.append(s.charAt(i));
}
}
//找出元音的位置,倒着替换
StringBuilder result=new StringBuilder();
String rvowels=vowels.toString();
int index=0;
for(int i=0;i<sl.length();i++){
char tmp=sl.charAt(i);
if(tmp=='a' || tmp=='e' || tmp=='i' || tmp=='o' || tmp=='u'){
result.append(rvowels.charAt(index++));
} else{
result.append(s.charAt(i));
}
}
return result.toString();
}
}