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: ["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.
- 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 List<String> fullJustify(String[] words, int maxWidth) {
List<String> result = new ArrayList<String>(); // store the result
List<String> list = new ArrayList<String>(); //store the words in the same line
int cnt = words[0].length();
list.add(words[0]);
int temp = 0;
for(int i = 1; i < words.length; i++){
temp = words[i].length() ;
if(cnt + temp + 1 <= maxWidth){
cnt += temp+1;
list.add(words[i]);
}else{
cnt = temp;
result.add(justify(list, maxWidth));
list.clear();
list.add(words[i]);
}
}
if(list.size() > 0){ // handle the last line,it won't be handled in the preceding cycle
int size = list.size();
int c = 1;
StringBuilder sb = new StringBuilder();
for(String str : list){
if(c++ == size){
sb.append(str);
}else{
sb.append(str).append(" ");
}
}
int remain = maxWidth - sb.length();
for(int i = 0; i < remain; i++){
sb.append(" ");
}
result.add(sb.toString());
}
return result;
}
//parameter : words in a line and the maxWidth
//return the sentence after justifying
private String justify(List<String> words, int maxWidth){
int cnt = words.size()-1;
int spaceLen = maxWidth;
for(String word : words){
spaceLen -= word.length();
}
StringBuilder sb = new StringBuilder();
if(cnt == 0){
sb.append(words.get(0));
for(int i = 0; i < spaceLen; i++){
sb.append(" ");
}
return sb.toString();
}
int tempSpaceLen = spaceLen;
int tempCnt = cnt;
int[] spaces = new int[cnt]; //store the number of spaces
for(int i = 0; i < cnt; i++){
if(tempSpaceLen % tempCnt != 0){
spaces[i] = tempSpaceLen / tempCnt + 1;
tempSpaceLen -= spaces[i];
tempCnt--;
}else{
spaces[i] = tempSpaceLen / tempCnt;
}
}
int temp = 0;
for(String word : words){ // create the justified sentence
if(temp == cnt){
sb.append(word);
break;
}
sb.append(word);
for(int i = 0; i < spaces[temp]; i++){
sb.append(" ");
}
temp++;
}
return sb.toString();
}