-
Notifications
You must be signed in to change notification settings - Fork 0
68. Text Justification
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.
解题思路为:
- Go through the words;
- Add with next word's length, if within range, append word and update len;
- If not, check how many words in this line, if only 1, append spaces;
- If more than 1, get total # of spaces and divide it with # of words-1;
- The quotient is # of spaces basically between each word;
- The remainder is # of sections that should add 1 more space;
- Then add string to result, clear line and add word of next line;
- Deal with last line after loop is over.
public class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> res = new ArrayList<>();
if(words == null || words.length == 0) return res;
List<String> line = new ArrayList<>();
int len = 0, div, mod;
for(int i = 0; i < words.length; i++) {
if(len + line.size() + words[i].length() <= maxWidth) {
// all word.length in line + whitespaces + next word.length <= maxWidth
line.add(words[i]);
len += words[i].length();
} else {
StringBuilder str = new StringBuilder();
if(line.size() == 1) {
// only 1 word in line
str.append(line.get(0));
for(int j = maxWidth - str.length(); j > 0; j--) str.append(" ");
} else {
div = (maxWidth - len) / (line.size() - 1);
mod = (maxWidth - len) % (line.size() - 1);
str.append(line.get(0));
for(int j = 1; j < line.size(); j++) {
for(int k = 0; k < div; k++) str.append(" ");
if(j <= mod) str.append(" ");
str.append(line.get(j));
}
}
res.add(str.toString());
line.clear();
// next line
line.add(words[i]);
len = words[i].length();
}
}
// last line
StringBuilder str = new StringBuilder();
str.append(line.get(0));
for(int i = 1; i < line.size(); i++) {
str.append(" " + line.get(i));
}
for(int i = maxWidth - str.length(); i > 0; i--) str.append(" ");
res.add(str.toString());
return res;
}
}