題目
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
click to show clarification.
Clarification:正統的做法就是自己去逐個找到每個單詞,從前往後還是從後往前其實都差不多,都要翻轉:要麼是翻轉字母(從後往前)、要麼翻轉單詞(從前往後)。
這裡給出的是用java自帶的split方法,幫助我們以“ ”進行切割,代碼看上去會比較簡潔明了。
代碼
public class ReverseWordsInAString {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
String[] array = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = array.length - 1; i >= 0; --i) {
if (!array[i].equals("")) {
sb.append(array[i]).append(" ");
}
}
return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
}
}