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.
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.
题目链接:https://leetcode.com/problems/text-justification/
题目大意:给一些字符串和一个数字L作为每行的最大字符数,要求每行尽量多的填入字符串,字符串和字符串间要尽量均等的留空格,没法均分的时候让左边的大于等于右边,最后一行要求左对齐,字符串之间只留一个空格,一个字符串单独占一行的情况下要求左对齐
public class Solution {
//curLen: 当前行字符串累加长度
//strCnt: 当前行字符串累加个数
//left, right: 当前行所选字符串数组的区间
//endCnt: 最后面要补的空格数
//spaceCnt: 当前行要添加的空格总数
//spaceEach: 每个字符串后面要添加的均分空格数
//extraCnt: 无法均分下,多出来的空格数
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> ans = new ArrayList<>();
int len = words.length;
if(len == 0) {
return ans;
}
int curLen = 0, strCnt = 0;
int left = 0, right = 0, pos = 0;
while(pos < len) {
if(curLen + words[pos].length() + strCnt <= maxWidth) {
curLen += words[pos].length();
strCnt ++;
right = pos;
pos ++;
}
if(pos == len || curLen + words[pos].length() + strCnt > maxWidth){
if(pos == len) {
int endCnt = 0;
StringBuffer sb = new StringBuffer();
if(left == right) {
sb.append(words[left]);
endCnt += words[left].length();
}
else {
for(int j = left; j < right; j++) {
sb.append(words[j] + " ");
endCnt += words[j].length() + 1;
}
sb.append(words[right]);
endCnt += words[right].length();
}
while(endCnt < maxWidth) {
sb.append(" ");
endCnt ++;
}
ans.add(sb.toString());
return ans;
}
else {
int spaceCnt = maxWidth - curLen;
int spaceEach = (strCnt > 2) ? spaceCnt / (strCnt - 1) : spaceCnt;
int extraCnt = 0;
if(strCnt > 2 && spaceCnt % (strCnt - 1) != 0) {
extraCnt = spaceCnt % (strCnt - 1);
}
StringBuffer sb = new StringBuffer();
sb.append(words[left]);
for(int j = 0; j < spaceEach; j++) {
sb.append(" ");
}
if(extraCnt > 0) {
sb.append(" ");
extraCnt --;
}
for(int j = left + 1; j < right; j++) {
sb.append(words[j]);
for(int k = 0; k < spaceEach; k++) {
sb.append(" ");
}
if(extraCnt > 0) {
sb.append(" ");
extraCnt --;
}
}
if(left < right) {
sb.append(words[right]);
}
ans.add(sb.toString());
if(pos != len) {
strCnt = 0;
curLen = 0;
left = pos;
right = pos;
}
}
}
}
return ans;
}
}