Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
思路
用stack 或者 遍歷時(shí)從后往前遍歷
注意
給定的string可能是由多個(gè)空格隔開的揣非,直接用slipt(" ")會得到[, , , a, , , b]
,不是我們想要的。
必須用s.split("\\s+")
這樣split多個(gè)空格
public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return s;
}
//split by multiple space
String[] temp = s.split("\\s+");
System.out.print(Arrays.toString(temp));
StringBuilder result = new StringBuilder();
for (int i = temp.length - 1; i >= 0; i--) {
result.append(temp[i]).append(" ");
}
String res = result.toString();
return res.trim();
}
}