码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 68: Text Justification

时间:2017-09-05 13:33:06      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:end   count   bsp   char   style   last   logs   int   bre   

class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {
        List<String> result = new ArrayList<>();
        if (words.length == 0) {
            return result;
        }
        int index = 0;
        while (index < words.length) {
            int charCount = words[index].length();
            int last = index + 1;
            while (last < words.length) {
                if (words[last].length() + charCount + 1 > maxWidth) {
                    break;
                }
                charCount += words[last++].length() + 1;
            }
            
            StringBuilder line = new StringBuilder();
            int wordCount = last - index;
            if (last == words.length || wordCount == 1) {
                for (int i = index; i < last; i++) {
                    line.append(words[i] + " ");
                }
                line.setLength(line.length() - 1);
                for (int i = line.length(); i < maxWidth; i++) {
                    line.append(" ");
                }
            } else {
                int space = (maxWidth - charCount) / (wordCount - 1);
                int rest = (maxWidth - charCount) % (wordCount - 1);
                for (int i = index; i < last; i++) {
                    line.append(words[i]);
                    if (i < last - 1) {
                        for (int j = 0; j <= (space + ((i - index) < rest ? 1 : 0)); j++) {
                            line.append(" ");
                        }
                    }
                }
            }
            result.add(line.toString());
            index = last;
        }
        
        return result;
    }
}

 

LeetCode 68: Text Justification

标签:end   count   bsp   char   style   last   logs   int   bre   

原文地址:http://www.cnblogs.com/shuashuashua/p/7478074.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!