题解 | #翻转单词序列#

翻转单词序列

https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3

import java.util.Stack;
public class Solution {
    public String ReverseSentence(String str) {
        // 可以把一个一个单词放入栈内,然后弹出
        Stack<String> words = new Stack<>();
        String res  = new String();
        String [] strings = str.split(" ");
        for(int i = 0; i < strings.length ; i++){
            words.push(strings[i]);
        }
        StringBuilder sb = new StringBuilder();
        while(words.size() > 1){
            sb.append(words.pop()).append(" ");
        }
        sb.append(words.pop());
        return sb.toString();
        
    }
}

关键点,用split把单词分开,装入栈,这个可以实现倒序。注意最后一个不要加空格。

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务