MCPcopy Create free account
hub / github.com/Blankj/awesome-java-leetcode / fullJustify

Method fullJustify

src/com/blankj/hard/_0044/Solution.java:58–98  ·  view source on GitHub ↗
(String[] words, int maxWidth)

Source from the content-addressed store, hash-verified

56// }
57
58 public List<String> fullJustify(String[] words, int maxWidth) {
59 int len = words.length;
60 if (len == 0) return Collections.emptyList();
61 List<String> ans = new ArrayList<>();
62 StringBuilder spaces = new StringBuilder();
63 for (int i = 0; i < maxWidth; ++i) {
64 spaces.append(" ");
65 }
66 int sLen = -1, left = 0;
67 for (int i = 0; i < len; ++i) {
68 if (sLen + words[i].length() + 1 <= maxWidth) {
69 sLen += words[i].length() + 1;
70 } else {
71 StringBuilder sub = new StringBuilder(words[left]);
72 int rest = maxWidth - sLen;
73 int seg = i - left;
74 if (seg == 0) {
75 sub.append(spaces.substring(0, rest));
76 } else {
77 int leastSpace = rest / seg + 1;
78 int restSpace = rest % seg;
79 for (int j = left + 1; j < i; ++j) {
80 if (restSpace-- > 0) {
81 sub.append(spaces.substring(0, leastSpace + 1)).append(words[j]);
82 } else {
83 sub.append(spaces.substring(0, leastSpace)).append(words[j]);
84 }
85 }
86 }
87 ans.add(sub.toString());
88 left = i;
89 sLen = words[i].length();
90 }
91 }
92 StringBuilder sub = new StringBuilder(words[left]);
93 for (int i = left + 1; i < len; ++i) {
94 sub.append(" ").append(words[i]);
95 }
96 ans.add(sub + spaces.substring(0, maxWidth - sub.length()));
97 return ans;
98 }
99
100
101 public static void main(String[] args) {

Callers 1

mainMethod · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected