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 exactly L 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: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.
Return the formatted lines as:
[
"This is an",
"example of text",
"justification. "
]
Idea: Brute force. Accumulate the length of the words, if the total length is above L or reach the end of the file, add spaces. There are two cases:
1) one word a line or the end of the file, left alignment (append one space for each word, then add empty space to L length.
2) the others: calculate the average number of spaces per word, first a few words need average+1, the other words need the average number, the last word does not append anything.
Time: O(n) Space: O(1)
Code:
public class Solution {
public List<String> fullJustify(String[] words, int L) {
List<String> result=new ArrayList<String>();
int curLength=0;
int lastI=0;
int wordCount=words.length;
for(int i=0;i<=wordCount;i++)
{
if(i==wordCount||curLength+words[i].length()+i-lastI>L)
{
StringBuilder builder=new StringBuilder();
int spaceCount=L-curLength;
int spaceSlot=i-lastI-1;
if(spaceSlot==0||i==wordCount)
{
for(int j=lastI;j<i;j++)
{
builder.append(words[j]);
if(j!=i-1)
appendSpace(builder,1);
}
appendSpace(builder,L-builder.length());
}
else
{
int spaceEach=spaceCount/spaceSlot;
int spaceExtra=spaceCount%spaceSlot;
for(int j=lastI;j<i;j++)
{
builder.append(words[j]);
if(j!=i-1)
{
appendSpace(builder,spaceEach+(j-lastI<spaceExtra?1:0));
}
}
}
result.add(builder.toString());
lastI=i;
curLength=0;
}
if(i<wordCount)
curLength+=words[i].length();
}
return result;
}
public void appendSpace(StringBuilder builder,int n)
{
for(int i=0;i<n;i++)
builder.append(' ');
}
}
No comments:
Post a Comment