1. 程式人生 > >LeetCode 68: Text Justification

LeetCode 68: Text Justification

pac maxwidth int tle char idt setlength set ace

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