Leetcode 68. Text Justification

Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ‘ ‘ when necessary so that each line has exactly L characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is inserted between words.

For example,
words: [“This”, “is”, “an”, “example”, “of”, “text”, “justification.”]
L: 16.
Return the formatted lines as:
[
“This is an”,
“example of text”,
“justification. “
]

1、算出当前行能放的单词数和所用长度;2、如果当前行将包括最后一个单词或者只包含一个单词,则右边不全空格;3、否则,算出单词间平均补全的空格数,以及左侧需要额外加1的空格位置。

public List<String> fullJustify(String[] words, int maxWidth) {
    List<String> res = new ArrayList<>();
    if (words == null || words.length == 0) {
        return res;
    }

    for (int index = 0; index < words.length; ) {
        StringBuilder buff = new StringBuilder();
        int count = words[index].length();
        int last = index + 1;
        while (last < words.length && count + 1 + words[last].length() <= maxWidth) {
            count += 1 + words[last].length();
            last++;
        }

        int diff = last - index - 1;
        if (last == words.length || diff == 0) {
            for (int i = index; i < last; i++) {
                buff.append(words[i] + ' ');
            }
            buff.deleteCharAt(buff.length() - 1);
            for (int i = buff.length() + 1; i <= maxWidth; i++) {
                buff.append(' ');
            }
        } else {
            int spaces = (maxWidth - count) / diff;
            int left = (maxWidth - count) % diff;
            for (int i = index; i < last; i++) {
                buff.append(words[i]);
                if (i < last - 1) {
                    for (int j = 0; j <= spaces + (i - index < left ? 1 : 0); j++) {
                        buff.append(' ');
                    }
                }
            }
        }

        res.add(buff.toString());
        index = last;
    }

    return res;
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/8961b9046d80
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞