LeetCode 151. 翻转字符串里的单词

2019-06-06  本文已影响0人  不会游泳的金鱼_

题目

给定一个字符串,逐个翻转字符串中的每个单词。

示例 1:

输入: "the sky is blue"
输出: "blue is sky the"

示例 2:

输入: " hello world! "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。

示例 3:

输入: "a good example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

说明:

思路

用栈结构即可,将字符串按照空格分割,把所有非空格单词和一个空格压入栈中,然后出栈重新组合成字符串即可。

代码

class Solution {
    public String reverseWords(String s) {
        if(s == null || s.trim().equals("")) return "";
        Stack<String> stack = new Stack<>();
        for(String temp :s.split(" ")) {
            if(!temp.trim().equals("")){
                stack.push(temp);
                stack.push(" ");
            }
        }
        stack.pop();
        StringBuffer sb = new StringBuffer();
        while(!stack.isEmpty()){
            sb.append(stack.pop());
        }
        return sb.toString();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读