Leetcode Reverse Words in a String

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".


解题思路:

用trim() 和splite("\\s+")把String 切割成一个一个word, 然后用StringBuilder 重建String. O(n) time and O(n) Space


Java code:

 public String reverseWords(String s) {
        if( s == null || s.length() == 0 ){
            return "";
        }
        String[] splited = s.trim().split("\\s+");
        int len = splited.length;
        StringBuilder sb = new StringBuilder();
        for(int i = len-1; i >= 0; i--){
            sb.append(splited[i] + " ");
        }
        return sb.toString().trim();
    }

Reference:

1. https://leetcode.com/discuss/56712/straightforward-java-solution-using-split

 

posted @ 2015-10-11 02:35  茜茜的技术空间  阅读(136)  评论(0编辑  收藏  举报