1 public class Solution {
2 public ArrayList<String> fullJustify(String[] words, int L) {
3 // IMPORTANT: Please reset any member data you declared, as
4 // the same Solution instance will be reused for each test case.
5 int wordsCount = words.length;
6 ArrayList<String> result = new ArrayList<String>();
7 int curLen = 0;
8 int lastI = 0;
9 for (int i = 0; i <= wordsCount; i++) {
10 if (i == wordsCount || curLen + words[i].length() + i - lastI > L) {
11 StringBuffer buf = new StringBuffer();
12 int spaceCount = L - curLen;
13 int spaceSlots = i - lastI - 1;
14 if (spaceSlots == 0 || i == wordsCount) {
15 for(int j = lastI; j < i; j++){
16 buf.append(words[j]);
17 if(j != i - 1)
18 appendSpace(buf, 1);
19 }
20 appendSpace(buf, L - buf.length());
21 } else {
22 int spaceEach = spaceCount / spaceSlots;
23 int spaceExtra = spaceCount % spaceSlots;
24 for (int j = lastI; j < i; j++) {
25 buf.append(words[j]);
26 if (j != i - 1)
27 appendSpace(buf, spaceEach + (j - lastI < spaceExtra ? 1 : 0));
28 }
29 }
30 result.add(buf.toString());
31 lastI = i;
32 curLen = 0;
33 }
34 if (i < wordsCount)
35 curLen += words[i].length();
36 }
37 return result;
38 }
39
40 private void appendSpace(StringBuffer sb, int count) {
41 for (int i = 0; i < count; i++)
42 sb.append(' ');
43 }
44 }