-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtextJustification.java
More file actions
71 lines (69 loc) · 1.63 KB
/
textJustification.java
File metadata and controls
71 lines (69 loc) · 1.63 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
public List<String> fullJustify(String[] words, int L) {
if(words == null || words.length == 0) return new ArrayList<String>();
int count = 0;
List<String> l = new ArrayList<String>();
List<String> wordsList = new ArrayList<String>();
for(String s : words){
if(count + s.length() > L){
addLines(wordsList, l, L);
wordsList.clear();
wordsList.add(s);
count = s.length() + 1;
}else{
count += s.length() + 1;
wordsList.add(s);
}
}
if(!wordsList.isEmpty()){
String s = "";
int spaceLength = L;
for( String word : wordsList){
spaceLength -= word.length();
}
for(int i = 0; i < wordsList.size() - 1; i++){
s += wordsList.get(i) + " ";
spaceLength--;
}
s += wordsList.get(wordsList.size() - 1);
while(spaceLength > 0){
s += " ";
spaceLength--;
}
l.add(s);
}
return l;
}
private void addLines(List<String> wordsList, List<String> l, int n){
if( wordsList.size() == 0)
return;
String s = "";
int spaceLength = n;
for( String word : wordsList){
spaceLength -= word.length();
}
int numSpace = wordsList.size() - 1;
if( numSpace == 0){
s += wordsList.get(0);
for(int i = spaceLength; i > 0; i--)
s += " ";
l.add(s);
return;
}
int baseSpace = spaceLength / numSpace;
int additionSpace = spaceLength % numSpace;
for( String word : wordsList){
s += word;
if(spaceLength > 0){
for(int i = baseSpace; i > 0; i--){
s += " ";
}
spaceLength -= baseSpace;
}
if(additionSpace > 0){
s += " ";
additionSpace--;
spaceLength -= 1;
}
}
l.add(s);
}