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(" +", " ");
//把多个空格替换为单个空格," +"表示连续的多个空格
trim();
//去掉String前面和尾部的空格 比如“ ab cdi "变成"ab cdi"
split(" ");
//用空格来分割String并返回成数组形式,比如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();
}
}