-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathJustifiedText.java
More file actions
88 lines (63 loc) · 1.89 KB
/
JustifiedText.java
File metadata and controls
88 lines (63 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package String;
import java.util.ArrayList;
/**
* Author - archit.s
* Date - 09/10/18
* Time - 12:24 PM
*/
public class JustifiedText {
public ArrayList<String> fullJustify(ArrayList<String> A, int B) {
ArrayList<String> r = new ArrayList<>();
if(A == null || A.size() == 0){
return A;
}
int last = 0;
int count = 0;
for(int i=0;i<A.size();i++){
count+= A.get(i).length();
if(count+i-last > B){
int eachLen = 1;
int extraLen = 0;
int wordLen = count - A.get(i).length();
int spaceLen = B - wordLen;
if(i-last-1 > 0){
eachLen = spaceLen/(i-last-1);
extraLen = spaceLen%(i-last-1);
}
StringBuilder sb = new StringBuilder();
for(int j=last;j<i-1;j++){
sb.append(A.get(j));
int temp = 0;
while(temp<eachLen){
sb.append(" ");
temp++;
}
while(extraLen > 0){
sb.append(" ");
extraLen--;
}
}
sb.append(A.get(i-1));
while(sb.length() < B){
sb.append(" ");
}
r.add(sb.toString());
last = i;
count = A.get(i).length();
}
}
StringBuilder sb = new StringBuilder();
for(int i=last;i<A.size()-1;i++){
sb.append(A.get(i));
sb.append(" ");
}
sb.append(A.get(A.size()-1));
while(sb.length() < B){
sb.append(" ");
}
if(sb.length()>0){
r.add(sb.toString());
}
return r;
}
}