68 Text Justification
https://leetcode.com/problems/text-justification/#/description
Given an array of words and a lengthL, format the text such that each line has exactlyLcharacters 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 exactlyLcharacters.
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 exceedLin length.
Hint:
Corner Cases:
- 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.
分析及代码
题目的要求
- 处理完每行都是刚好L个字符
- 如果后面有空白的,用space补全
- 一行里面的词间隔是均匀的,不均匀用space填写
- 最后一行全部左对齐,不需要调整
- 保证没有超过L长度的单词
代码
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> res = new ArrayList<>();
int index = 0;
int totalNumOfWords = words.length;
while(index < totalNumOfWords) {
int curLenSum = -1;
int endWordIndex = index;
for(; endWordIndex < totalNumOfWords && curLenSum + words[endWordIndex].length() + 1<= maxWidth; endWordIndex++) {
curLenSum += words[endWordIndex].length() + 1;
}
int spaceBetweenWords = 1;
int extraSpace = 0;
if(endWordIndex != index + 1 && endWordIndex != totalNumOfWords) { // more than one word in a line && not last line
spaceBetweenWords = (maxWidth - curLenSum) / (endWordIndex - index - 1) + 1;
extraSpace = (maxWidth - curLenSum) % (endWordIndex - index - 1);
}
StringBuilder sb = new StringBuilder(words[index]);
for(int i = index + 1; i < endWordIndex; i++) {
for(int j = spaceBetweenWords; j > 0; j--) {
sb.append(" ");
}
if(extraSpace-- > 0) {
sb.append(" ");
}
sb.append(words[i]);
}
int strLen = maxWidth - sb.length();
while(strLen-- > 0) {
sb.append(" ");
}
index = endWordIndex;
res.add(sb.toString());
}
return res;
}
自己写的思路也没错,就是特别啰嗦
注意的是endWordIndex是本行没有添加进去的第一个,而不是添加进去的最后一个