151. Reverse Words in a String

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();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容