LeetCode 68: Text Justification

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 68: Text Justification相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 68 Text Justification ----- java

[leetcode]68. Text Justification文字对齐

LeetCode -- 68.Text Justification

LeetCode 68: Text Justification

一天一道LeetCode#68. Text Justification

LeetCode 68. Text Justification