首页 > 代码库 > Text Justification
Text Justification
Given an array of words and a length L, format the text such that each line has exactlyL 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 class Solution { public List<String> fullJustify(String[] words, int L) { List<String>result=new LinkedList<String>(); if(words==null||words.length<1) { return result; } int i,j; for(i=0,j=0;i<words.length;i=j) { int wordsLen=0; while(j<words.length) { wordsLen+=words[j].length(); if(wordsLen+j-i>L) { break; } j++; } if(j<words.length) { wordsLen-=words[j].length(); } String s=""; if(j-i==1) { s=words[i]; } else { int p=(j==words.length)?1:(L-wordsLen)/(j-i-1); int remaining=(j==words.length)?0:L-wordsLen-p*(j-i-1); String space=""; while(p-->0) { space+=" "; } for(int k=i;k<j-1;k++) { s+=words[k]+space; if(remaining>0) { remaining--; s+=" "; } } s+=words[j-1]; } while(s.length()<L) { s+=" "; } result.add(s); } return result; } }
Text Justification