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

Class Solution

src/com/blankj/hard/_0068/Solution.java:14–61  ·  view source on GitHub ↗

author: Blankj blog : http://blankj.com time : 2017/11/01 desc :

Source from the content-addressed store, hash-verified

12 * </pre>
13 */
14public class Solution {
15
16 public List<String> fullJustify(String[] words, int maxWidth) {
17 int len = words.length;
18 List<String> ans = new ArrayList<>();
19 StringBuilder spaces = new StringBuilder();
20 for (int i = 0; i < maxWidth; ++i) {
21 spaces.append(" ");
22 }
23 int curLen = -1, start = 0;
24 for (int i = 0; i < len; ++i) {
25 if (curLen + words[i].length() + 1 <= maxWidth) {
26 curLen += words[i].length() + 1;
27 } else {
28 StringBuilder sub = new StringBuilder(words[start]);
29 int rest = maxWidth - curLen;
30 int l = i - start - 1;
31 if (l <= 0) {
32 sub.append(spaces.substring(0, rest));
33 } else {
34 int m = rest / l + 1;
35 int mod = rest % l;
36 for (int j = start + 1; j < i; ++j) {
37 if (mod-- > 0) {
38 sub.append(spaces.substring(0, m + 1)).append(words[j]);
39 } else {
40 sub.append(spaces.substring(0, m)).append(words[j]);
41 }
42 }
43 }
44 ans.add(sub.toString());
45 start = i;
46 curLen = words[i].length();
47 }
48 }
49 StringBuilder sub = new StringBuilder(words[start]);
50 for (int i = start + 1; i < len; ++i) {
51 sub.append(" ").append(words[i]);
52 }
53 ans.add(sub + spaces.substring(0, maxWidth - sub.length()));
54 return ans;
55 }
56
57 public static void main(String[] args) {
58 Solution solution = new Solution();
59 System.out.println(solution.fullJustify(new String[]{"This", "is", "an", "example", "of", "text", "justification."}, 16));
60 }
61}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected