LeetCode 68: Text Justification
阿新 • • 發佈:2017-09-05
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) { intcharCount = 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