一.问题描述
Given an input string, reverse the string word by word.
For example,
Given s = “the sky is blue”,
return “blue is sky the”.
二.我的解题思路
java的String类提供了较为丰富的方法,因此直接使用java的方法就可以较好的解决这个问题,如下:
public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
String[] arr = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = arr.length - 1; i >= 0; --i) {
if (!arr[i].equals("")) {
sb.append(arr[i]).append(" ");
}
}
return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
}
}