[LeetCode]68 Text Justification

https://oj.leetcode.com/problems/text-justification/

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

public class Solution {
    public List<String> fullJustify(String[] words, int L) {
        
        if (words == null || words.length == 0)
            return Collections.emptyList();
            
        // Assumes L >= words[any].length()
        
        List<String> result = new ArrayList<>();
        
        int curlinelen = 0;
        List<String> curline = new ArrayList<>();
        
        for (int i = 0 ; i < words.length ; i ++)
        {
            if (curlinelen + words[i].length() > L)
            {
                result.add(build(curline, L, false));
                curlinelen = 0;
                curline.clear();
            }
            
            curlinelen += words[i].length() + 1;
            curline.add(words[i]);
        }
        
        if (!curline.isEmpty())
        {
            result.add(build(curline, L, true));
        }
        
        return result;
    }
    
    private String build(List<String> strs, int L, boolean lastline)
    {
        int len = strs.size();
        StringBuilder sb = new StringBuilder();
        
        if (lastline || len == 1)
        {
            for (int i = 0 ; i < len ; i ++)
            {
                sb.append(strs.get(i));
                if (i != len - 1)
                    addSpaces(sb, 1);
            }
            addSpaces(sb, L - sb.length());
            return sb.toString();
        }
        else
        {
            int strlen = 0;
            for (String r : strs)
            {
                strlen += r.length();
            }
            
            // Base spaces between words
            int basespaces = (L - strlen) / (len - 1);
            
            // If i < extraspacenum, put extra ' ' in between.
            int extraspacenum = (L - strlen) % (len - 1);
            
            for (int i = 0 ; i < len ; i ++)
            {
                sb.append(strs.get(i));
                if (i != len - 1)
                {
                    addSpaces(sb, basespaces);
                    if (i < extraspacenum)
                        addSpaces(sb, 1);
                }
            }
        }
        return sb.toString();
    }
    
    private void addSpaces(StringBuilder sb, int n)
    {
        for (int i = 0 ; i < n ; i ++)
            sb.append(" ");
    }
}


你可能感兴趣的:(LeetCode)