题目描述
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
解题思路
最直接的想法就是使用split函数将字符串以“”分割。但再实际过程中出现了麻烦。
测试输入会给一些比较bug的用例,比如“ ”,“ a”," a ".....
而" a ".split(" ")的得到数组array.length = 4。这说明数组中有一些元素的值为“”。我们必须将这些考虑进去。
代码
public String reverseWords(String s) {
String result = "";
if (s == null || s.equals(""))
return s;
String[] array = s.split(" ");
if (array == null || array.length == 0) {
return "";
}
for (int i = array.length - 1; i >= 0; i--) {
if(!array[i].equals("")){
if(result.equals("")){
result = result + array[i];
} else{
result = result + " " + array[i];
}
}
}
return result;
}