您的位置:首页 > 其它

Text Justification

2015-07-28 21:26 253 查看
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.

public class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
ArrayList<String> result = new ArrayList<String>();
int len=words.length,curLen=0,lastI=0;
for(int i=0;i<=len;i++){
if(i==len||curLen+words[i].length()+i-lastI>maxWidth){
StringBuffer buf=new StringBuffer();
int spaceLen=maxWidth-curLen;
int spaceSlots=i-lastI-1;
if(spaceSlots==0||i==len){
for(int j=lastI;j<i;j++){
buf.append(words[j]);
if(j!=i-1)
appendSpace(buf, 1);
}
appendSpace(buf, maxWidth-buf.length());
}else {
int spaceEach=spaceLen/spaceSlots;
int sapceExtra=spaceLen%spaceSlots;
for(int j=lastI;j<i;j++){
buf.append(words[j]);
if(j!=i-1)
appendSpace(buf, spaceEach+(j-lastI<sapceExtra?1:0));
}
}
result.add(buf.toString());
lastI=i;
curLen=0;
}
if(i<len)
curLen+=words[i].length();
}
return result;
}
private void appendSpace(StringBuffer sb, int count) {
for (int i = 0; i < count; i++)
sb.append(' ');
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: