Skip to content

Commit d635163

Browse files
Kartik SiddhabathulaKartik Siddhabathula
authored andcommitted
Program to given a string of words and maxwidth, format the text such that each line has exactly L characters and is fully (left and right) justified.
1 parent 8e06109 commit d635163

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

ArraysStrings/TextJustification.java

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package programcreek.ArraysStrings;
2+
3+
/*
4+
*
5+
*/
6+
7+
import java.util.*;
8+
9+
public class TextJustification {
10+
11+
public static void main(String[] args) {
12+
String[] input = {"Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do."};
13+
int len = 20;
14+
List<String> result = JustifyString(input,len);
15+
printResult(result);
16+
}
17+
18+
private static List<String> JustifyString(String[] words, int maxWidth) {
19+
List<String> result = new ArrayList<String>();
20+
21+
if(words==null || words.length==0){
22+
return result;
23+
}
24+
25+
26+
int count=0;
27+
int last=0;
28+
for(int i=0; i<words.length; i++){
29+
count = count + words[i].length();
30+
31+
if(count+i-last>maxWidth){
32+
int wordsLen = count-words[i].length();
33+
int spaceLen = maxWidth-wordsLen;
34+
int eachLen = 1;
35+
int extraLen = 0;
36+
37+
if(i-last-1>0){
38+
eachLen = spaceLen/(i-last-1);
39+
extraLen = spaceLen%(i-last-1);
40+
}
41+
42+
StringBuilder sb = new StringBuilder();
43+
44+
for(int k=last; k<i-1; k++){
45+
sb.append(words[k]);
46+
47+
int ce = 0;
48+
while(ce<eachLen){
49+
sb.append(" ");
50+
ce++;
51+
}
52+
53+
if(extraLen>0){
54+
sb.append(" ");
55+
extraLen--;
56+
}
57+
}
58+
59+
sb.append(words[i-1]);//last words in the line
60+
//if only one word in this line, need to fill left with space
61+
while(sb.length()<maxWidth){
62+
sb.append(" ");
63+
}
64+
65+
result.add(sb.toString());
66+
67+
last = i;
68+
count=words[i].length();
69+
}
70+
}
71+
72+
StringBuilder sb = new StringBuilder();
73+
74+
for(int i=last; i<words.length-1; i++){
75+
count = count+words[i].length();
76+
sb.append(words[i]+" ");
77+
}
78+
79+
sb.append(words[words.length-1]);
80+
while(sb.length()<maxWidth){
81+
sb.append(" ");
82+
}
83+
result.add(sb.toString());
84+
85+
return result;
86+
}
87+
private static void printResult(List<String> result) {
88+
for(int i=0;i<result.size();i++) {
89+
System.out.println(result.get(i));
90+
}
91+
}
92+
}

0 commit comments

Comments
 (0)