2014年11月23日星期日

[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".
One way is to use the split function to split the words into an array. And then combine the words. In order to split multi spaces, we need to use "\\s+" instead of simple " ".


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

Another way is to write it in place without split function. We could first trim the string to remove the leading and tailing spaces, this would ease the translation.

    public String reverseWords(String s) {
        s = s.trim();
        if(s.length() == 0)
            return s;
        int p1 = s.length() - 1, p2 = s.length() - 1;
        StringBuffer sb = new StringBuffer();
        while(p1 >= 0) {
            while(p1 >= 0 && s.charAt(p1) == ' ')
                p1--;
            p2 = p1;
            while(p1 >= 0 && s.charAt(p1) != ' ')
                p1--;
            sb.append(s.substring(p1+1, p2+1));
            if(p1 != p2)
                sb.append(" ");
        }
        String res = sb.toString();
        // remove the last space
        res = res.substring(0, res.length() - 1);
        return res;
    }

I prefer the first method since it is much cleaner, however the second one is often asked as a follow up.

没有评论:

发表评论