151. 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".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

click to show clarification.

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.

链接: http://leetcode.com/problems/reverse-words-in-a-string/

题解:

反转单词。这道题乍一看很简单,实际上也很简单。假如可以使用Java库函数split和trim的话,代码不会很长。另外,如果不能使用库函数,我们还可以有其他的方法。比如像可以先用字符串生成字符数组,反转整个数组,再反转每个单词,  或者是从后向前一个一个insert到一个StringBuilder里,等等。

Time Complexity - O(n), Space Complexity - O(n)

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

 

二刷:

还是用库函数做吧。假如考到的话要问清楚clarification questions。比如是否前后有trailing zeroes,或者是出现多个空格怎么办.

Java:

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

 

Reference:

posted @ 2015-05-09 12:12  YRB  阅读(341)  评论(0编辑  收藏  举报