2014年4月29日 星期二

[LeetCode] Reverse Words in a String

Problem:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Solution:O(n)
public class Solution {
    public String reverseWords(String s) {
        if(s == null || !s.contains(" "))
            return s;
        String s2 = s.replaceAll(" +"," ").trim();
        String [] set = s2.split(" ");
        StringBuffer buf = new StringBuffer();
       
        for(int i= set.length-1; i>=0;i--){
            if(i !=set.length-1)
                buf.append(" ");
            buf.append(set[i]);   
        }
        return buf.toString();
    }
}

沒有留言:

張貼留言