Medium:
Given an input string, reverse the string word by word.
For example,Given s = "the sky is blue"
,
return "blue is sky the"
.
Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?Reduce them to a single space in the reversed string.
這道題基本上就是教你用幾個平常不常用但是很有用的String的API:
replaceAll(" +", " ");
//把多個空格替換為單個空格," +"表示連續(xù)的多個空格
trim();
//去掉String前面和尾部的空格 比如“ ab cdi "變成"ab cdi"
split(" ");
//用空格來分割String并返回成數(shù)組形式,比如s= "a b c d e", s.split(" ") = {a,b,c,d,e}.
public class Solution {
public String reverseWords(String s) {
s = s.trim().replaceAll(" +", " ");
String[] as = s.split(" ");
Stack<String> stack = new Stack<>();
for(String str : as){
stack.push(str);
}
StringBuilder res = new StringBuilder();
while (!stack.isEmpty()){
String curt = stack.pop();
res.append(curt);
res.append(" ");
}
return res.toString().trim();
}
}