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 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:
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.
Corner Cases:
Solution:O(n)- A line other than the last line might contain only one word. What should you do in this case?
In this case, that line should be left-justified.
public class Solution {
public ArrayList<String> fullJustify(String[] words, int L) {
ArrayList<String> list = new ArrayList<String>();
if(words == null || words.length == 0)
return list;
if(words.length == 1 && words[0].length() ==0){
String buf = "";
for(int i=0; i<L;i++)
buf+=" ";
list.add(buf);
return list;
}
int len = 0;
int start = 0;
for(int i=0; i< words.length; i++){
int count = i-start;
if( (words[i].length() + len + count) <= L){
len+= words[i].length();
}else{
list.add(getString(words,L,len,start,i,false));
len = words[i].length();
start = i;
}
}
list.add(getString(words,L,len,start,words.length,true));
return list;
}
public String getString(String[] words, int L, int len, int start, int end, boolean islast){
int space = L-len;
String buf = words[start];
int count = end-start;
for(int t=start+1; t<end;t++){
int s = space/(end-t);
if(islast){
s = 1;
}else{
if(space %(end-t) != 0 ){
s+=1;
}
}
for(int k=0; k<s;k++){
buf+=" ";
}
buf+=words[t];
space-=s;
}
for(int k=0; k<space;k++){
buf+=" ";
}
return buf;
}
}
沒有留言:
張貼留言