|
| 1 | +// https://leetcode.com/problems/text-justification |
| 2 | + |
| 3 | +public class Solution { |
| 4 | + public int getLineWidth(List<String> words) { |
| 5 | + int width = 0; |
| 6 | + |
| 7 | + for (String word : words) { |
| 8 | + width += word.length() + 1; |
| 9 | + } |
| 10 | + |
| 11 | + return width; |
| 12 | + } |
| 13 | + |
| 14 | + public String formatLine(List<String> words, int maxWidth, boolean lastSentence) { |
| 15 | + StringBuilder sb = new StringBuilder(); |
| 16 | + |
| 17 | + if (words.size() == 1 || lastSentence) { // left-justified single-word line |
| 18 | + for (String word : words) { |
| 19 | + sb.append(word); |
| 20 | + if (sb.length() < maxWidth) { |
| 21 | + sb.append(" "); |
| 22 | + } |
| 23 | + } |
| 24 | + while (sb.length() < maxWidth) { |
| 25 | + sb.append(" "); |
| 26 | + } |
| 27 | + } else { |
| 28 | + List<StringBuilder> wordBuilder = new ArrayList<>(); |
| 29 | + int wordLength = 0; |
| 30 | + for (String word : words) { |
| 31 | + wordBuilder.add(new StringBuilder(word)); |
| 32 | + wordLength += word.length(); |
| 33 | + } |
| 34 | + |
| 35 | + int spaceToDist = maxWidth - wordLength; |
| 36 | + int i = 0; |
| 37 | + |
| 38 | + while (spaceToDist > 0) { |
| 39 | + wordBuilder.get(i).append(" "); |
| 40 | + spaceToDist--; |
| 41 | + i++; |
| 42 | + if (i == words.size() - 1) { |
| 43 | + i = 0; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + for (StringBuilder wBuilder : wordBuilder) { |
| 48 | + sb.append(wBuilder); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return sb.toString(); |
| 53 | + } |
| 54 | + |
| 55 | + public List<String> fullJustify(String[] words, int maxWidth) { |
| 56 | + List<String> lines = new ArrayList<>(); |
| 57 | + |
| 58 | + if (maxWidth == 0) { |
| 59 | + lines.add(""); |
| 60 | + return lines; |
| 61 | + } |
| 62 | + |
| 63 | + List<String> cLine = new ArrayList<>(); |
| 64 | + |
| 65 | + for (String word : words) { |
| 66 | + if (getLineWidth(cLine) + word.length() <= maxWidth) { |
| 67 | + cLine.add(word); |
| 68 | + } else { |
| 69 | + lines.add(formatLine(cLine, maxWidth, false)); |
| 70 | + cLine = new ArrayList<>(); |
| 71 | + cLine.add(word); |
| 72 | + } |
| 73 | + } |
| 74 | + lines.add(formatLine(cLine, maxWidth, true)); |
| 75 | + |
| 76 | + return lines; |
| 77 | + } |
| 78 | +} |
0 commit comments