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.

這道題基本上就是教你用幾個(gè)平常不常用但是很有用的String的API:

replaceAll(" +", " "); //把多個(gè)空格替換為單個(gè)空格," +"表示連續(xù)的多個(gè)空格
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();
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容