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.
可以很容易找到分界词 an text
找到分界词an后可以看到需要把8个空格分配成两份
8/2 : 4 4
10/3 : 4 3 3
11/3 : 4 4 3
生成过程
(11)/3 = 4 :4 (取上界)
11-4= 7
( 7)/2 = 4 :4 (取上界)
7-4 = 3
( 3)/1 = 3 :3
当前空格数 / 份数 的上界限为当前应打印的空格数
当前空格数 - 当前应打印的空格数 = 剩余空格数
份数 = 0时跳出循环
假如这一行有一个单词:那么有1个空格段
假如这一行有两个单词:那么也是有1个空格段
假如这一行有三个单词:那么有2个空格段
…………
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> result = new ArrayList<String>();
StringBuffer tempStringBuffer = new StringBuffer();
for(int i = 0;i < words.length;){
int j = i+1;
int currentLength = words[i].length();
//为j定位
while(j < words.length && currentLength + 1 + words[j].length() <= maxWidth) {
currentLength += words[j].length() + 1;
j++;
}
//输出当前i 到 j之间单词
if(j == words.length){//是末尾行
tempStringBuffer.append(words[i++]);
while(i < j)
tempStringBuffer.append(" " + words[i++]);
int extraSpace = maxWidth - currentLength;
while(extraSpace-- > 0)
tempStringBuffer.append(" ");
}
else{//不是末尾行
tempStringBuffer.append(words[i]);
int blockNum = j - i -1;
int extraSpace = maxWidth - currentLength;
if(blockNum == 0){//该行只有一个单词
while(extraSpace -- > 0)
tempStringBuffer.append(" ");
}
else{//该行有多个单词
for(int k = i+1;k < j;k++){
int temp = (int)Math.ceil(extraSpace/(float)blockNum);
extraSpace -= temp;
blockNum--;
while(temp-- > 0) tempStringBuffer.append(" ");
tempStringBuffer.append(" "+words[k]);
}
}
i = j;
}
//将当前行加入结果集中
result.add(tempStringBuffer.toString());
tempStringBuffer.setLength(0);
}
return result;
}
本文介绍了一种用于实现文本全对齐的算法,确保每行文字长度固定,并且能够均匀分布单词间的空格。特别关注了如何处理最后一行的特殊格式要求。
352

被折叠的 条评论
为什么被折叠?



