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、算出當前行能放的單詞數(shù)和所用長度;2、如果當前行將包括最后一個單詞或者只包含一個單詞,則右邊不全空格;3、否則,算出單詞間平均補全的空格數(shù),以及左側需要額外加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;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容