Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces
' '
when necessary so that each line has exactlyL characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is inserted between words.
For example,
words:
L:
words:
["This", "is", "an", "example", "of", "text", "justification."]
L:
16
.
Return the formatted lines as:
[ "This is an", "example of text", "justification. " ]
Note: Each word is guaranteed not to exceed L in length.
Solution 1: Need to be extreme careful with all corner case.
public class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> res=new ArrayList<>();
int n=words.length, i=0, l=0;
for (int j=0; j<n; j++) {
l+=words[j].length();
if (l+j-i>maxWidth) {
l-=words[j].length();
if (j-1==i) {
char[] blank=new char[maxWidth-l];
Arrays.fill(blank,' ');
res.add(words[i]+new String(blank));
}
else {
int w=(maxWidth-l)/(j-i-1);
int ex=(maxWidth-l)%(j-i-1);
char[] blank=new char[w];
Arrays.fill(blank,' ');
StringBuilder one=new StringBuilder();
for (int k=i; k<j; k++) {
one.append(words[k]);
if (k!=j-1) one.append(blank);
if (k-i<ex) one.append(' ');
}
res.add(one.toString());
}
i=j;
l=words[j].length();
}
}
char[] blank=new char[maxWidth-l-n+i+1];
Arrays.fill(blank,' ');
StringBuilder one=new StringBuilder();
for (int k=i; k<n; k++) {
one.append(words[k]);
if (k==n-1) one.append(blank);
else one.append(' ');
}
res.add(one.toString());
return res;
}
}
没有评论:
发表评论