首页 > 代码库 > [LeetCode]151 Reverse Words in a String

[LeetCode]151 Reverse Words in a String

https://oj.leetcode.com/problems/reverse-words-in-a-string/

http://blog.csdn.net/linhuanmars/article/details/20982463

public class Solution {
    
    public String reverseWords(String s) {
        
        // Solution A:
        return reverseWords_Char(s);
        
        // Solution B:
        // return reverseWords_Split(s);
    }
    
    /////////////////////
    // Solution A: Char
    //
    public String reverseWords_Char(String s) {
        
        if (s == null)
            return null;
        
        char[] chars = s.toCharArray();
        int len = chars.length;
        
        StringBuilder sb = new StringBuilder();
        StringBuilder subsb = new StringBuilder();
        
        for (int i = 0 ; i < len ; i ++)
        {
            char c = chars[i];
            if (c == ‘ ‘)
            {
                if (subsb.length() > 0)
                {
                    if (sb.length() == 0)
                        sb.append(subsb.toString());
                    else
                        sb.insert(0, subsb.toString() + " ");    
                    subsb = new StringBuilder();
                }
            }
            else
                subsb.append(c);
        }
        if (subsb.length() > 0)
        {
            if (sb.length() == 0)
                sb.append(subsb.toString());
            else
                sb.insert(0, subsb.toString() + " ");    
        }
        
        return sb.toString().trim();
    }

    /////////////////////
    // Solution B: split
    //
    public String reverseWords_Split(String s) 
    {
        if (s == null)
            return null;
        s = s.trim();
        if (s.isEmpty())
            return "";

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


[LeetCode]151 Reverse Words in a String