File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .ArrayList ;
2+
3+ public class TextJustification {
4+ public ArrayList <String > fullJustify (String [] words , int L ) {
5+ ArrayList <String > ret = new ArrayList <String >();
6+ int length = words .length ;
7+ if (length == 0 ) return ret ;
8+ int start = 0 , end = start ;
9+ int len = 0 ;
10+ while (start < length ) {
11+ StringBuffer line = new StringBuffer ();
12+ while (end < length ) {
13+ int sl = words [end ].length ();
14+ if (len + (end - start ) + sl > L ) {
15+ break ;
16+ }
17+ len += sl ;
18+ end ++;
19+ }
20+ end --;
21+ if (end < start ) {
22+ end = start ;
23+ }
24+ if (start == end ) {
25+ line .append (words [start ]);
26+ int spaceCount = L - words [start ].length ();
27+ for (int i = 0 ; i < spaceCount ; i ++) {
28+ line .append (' ' );
29+ }
30+ ret .add (line .toString ());
31+ } else {
32+ boolean lastLine = end == length - 1 ;
33+ int spaceBase = lastLine ? 1 : (L - len ) / (end - start );
34+ int bonus = lastLine ? 0 : L - len - spaceBase * (end - start );
35+ line .append (words [start ]);
36+ for (int i = start + 1 ; i <= end ; i ++) {
37+ for (int j = 0 ; j < spaceBase ; j ++) {
38+ line .append (' ' );
39+ }
40+ if (bonus > 0 ) {
41+ line .append (' ' );
42+ bonus --;
43+ }
44+ line .append (words [i ]);
45+ }
46+ if (lastLine ) {
47+ for (int i = 0 ; i < L - len - (end - start ); i ++) {
48+ line .append (' ' );
49+ }
50+ }
51+ ret .add (line .toString ());
52+ }
53+ start = end + 1 ;
54+ end = start ;
55+ len = 0 ;
56+ }
57+ return ret ;
58+ }
59+ }
You can’t perform that action at this time.
0 commit comments