leetcode-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".
代码解析:
public class Solution {
public static String reverseVowels(String s) {
// if(s == null) return null;
int len = s.length();
char tmp;
//构造数组操作
char[] arr = s.toCharArray();
for(int i =0 ,j=len-1 ; i<j ;i++,j--){
char chi = arr[i];
if(!isVowels(chi)){
j++;
continue;
}
char chj = arr[j];
if(!isVowels(chj)){
i--;
continue;
}
if(isVowels(chi)&&isVowels(chj)){
//因为string是不可变的~~~!!!!所以不能赋值
tmp = arr[i];
arr[i] = arr[j];
arr[j]= tmp;
//s.charAt(i) = chj;
//上述形式为什么老是编译不过???
//因为String一旦定义好,就不可改变!!!!因此将String -> Arrays!!!
}
}
//char -> string ,使用 String.valueOf(), arrays.toString()返回的不是原样式的String
return String.valueOf(arr);
}
public static boolean isVowels(char ch){
if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U'||ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') return true;
return false;
}
}
总结:Array -> String三种方式:
1、String.valueOf(arr); //直接传入
2、new String(arr); //直接传入
3、sb = new StringBuilder();
sb.append(arr[i]); //依次传入
String -> array: str.toCharArray(); 字符数组
char -> int : i = char-'0';
int -> char : char = i+'0';