|
| 1 | +class Solution { |
| 2 | + public List<String> fullJustify(String[] words, int maxWidth) { |
| 3 | + if (words == null || words.length == 0) { |
| 4 | + return Collections.emptyList(); |
| 5 | + } |
| 6 | + |
| 7 | + List<String> result = new ArrayList<>(); |
| 8 | + int left = 0; |
| 9 | + |
| 10 | + while (left < words.length) { |
| 11 | + int right = findRight(left, words, maxWidth); |
| 12 | + result.add(justify(left, right, words, maxWidth)); |
| 13 | + left = right + 1; |
| 14 | + } |
| 15 | + |
| 16 | + return result; |
| 17 | + } |
| 18 | + |
| 19 | + private int findRight(int left, String[] words, int maxWidth) { |
| 20 | + int right = left; |
| 21 | + int sum = words[right].length(); |
| 22 | + ++right; |
| 23 | + |
| 24 | + while (right < words.length && (sum + 1 + words[right].length()) <= maxWidth) { |
| 25 | + sum += words[right].length() + 1; |
| 26 | + ++right; |
| 27 | + } |
| 28 | + |
| 29 | + return right - 1; |
| 30 | + } |
| 31 | + |
| 32 | + private String justify(int left, int right, String[] words, int maxWidth) { |
| 33 | + StringBuilder sb = new StringBuilder(); |
| 34 | + |
| 35 | + if (right - left == 0) { |
| 36 | + return padResult(words[left], maxWidth); |
| 37 | + } |
| 38 | + |
| 39 | + boolean isLastLine = right == words.length - 1; |
| 40 | + int numOfSpaces = right - left; |
| 41 | + int totalSpaces = maxWidth - wordsLength(left, right, words); |
| 42 | + |
| 43 | + String space = isLastLine ? " " : blank(totalSpaces / numOfSpaces); |
| 44 | + int remainder = isLastLine ? 0 : totalSpaces % numOfSpaces; |
| 45 | + |
| 46 | + for (int i = left; i <= right; i++) { |
| 47 | + sb.append(words[i]).append(space).append(remainder-- > 0 ? " " : ""); |
| 48 | + } |
| 49 | + |
| 50 | + return padResult(sb.toString().trim(), maxWidth); |
| 51 | + } |
| 52 | + |
| 53 | + private int wordsLength(int left, int right, String[] words) { |
| 54 | + int length = 0; |
| 55 | + |
| 56 | + for (int i = left; i <= right; i++) { |
| 57 | + length += words[i].length(); |
| 58 | + } |
| 59 | + |
| 60 | + return length; |
| 61 | + } |
| 62 | + |
| 63 | + private String padResult(String result, int maxWidth) { |
| 64 | + StringBuilder sb = new StringBuilder(); |
| 65 | + sb.append(result).append(blank(maxWidth - result.length())); |
| 66 | + |
| 67 | + return sb.toString(); |
| 68 | + } |
| 69 | + |
| 70 | + private String blank(int length) { |
| 71 | + StringBuilder sb = new StringBuilder(); |
| 72 | + for (int i = 0; i < length; i++) { |
| 73 | + sb.append(" "); |
| 74 | + } |
| 75 | + |
| 76 | + return sb.toString(); |
| 77 | + } |
| 78 | +} |
0 commit comments