`
zhang_xzhi_xjtu
  • 浏览: 536393 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode] ReverseWordsinaString

阅读更多
package leetcode;

import java.util.Stack;

/**
* <pre>
* Given an input string, reverse the string word by word.
*
* For example,
* Given s = "the sky is blue",
* return "blue is sky the".
* </pre>
*/
public class ReverseWordsinaString {

    public class Solution {
        public String reverseWords(String s) {
            String[] parts = s.split(" ");
            Stack<String> stack = new Stack<String>();
            for (String value : parts) {
                if (value == null || value.isEmpty())
                    continue;
                stack.push(value);
                stack.push(" ");
            }
            if (stack.isEmpty())
                return "";

            stack.pop();

            StringBuilder sb = new StringBuilder();
            while (!stack.isEmpty()) {
                sb.append(stack.pop());
            }
            return sb.toString();
        }
    }
}
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics