68. The left and right text alignment
Given an array and a word length maxWidth, reformat words, making each row has exactly maxWidth characters, and the left and right justified text.
You should use the "greedy algorithm" to place the given word; that is to say, as much as possible to place the words in each line. Available spaces when necessary, 'filled, such that each row has exactly maxWidth characters.
It requires a uniform distribution of the number of spaces between words as possible. If the spaces between words can not be evenly distributed in a row, the number of spaces placed left to the right than the number of spaces.
The last line of text should be left justified, and not insert extra spaces between words.
Description:
The word refers to the character sequence of non-space characters.
The length of each word is larger than 0, less than or equal maxWidth.
Enter the word array of words containing at least one word.
Example:
输入:
words = [“This”, “is”, “an”, “example”, “of”, “text”, “justification.”]
maxWidth = 16
输出:
[
“This is an”,
“example of text”,
"justification. "
]
示例 2:
Input:
words = [ "What", "MUST", "BE", "Acknowledgment", "of shall", "BE"]
maxWidth = 16
Output:
[
"What MUST BE",
"Acknowledgment",
"of shall BE"
]
explanation: Note the last line of the format should be "shall be" instead of "shall be",
because the last line should be left justified, instead of around it was not justified.
The second line is also left-justified, since this line contains only one word.
Example 3:
输入:
words = [“Science”,“is”,“what”,“we”,“understand”,“well”,“enough”,“to”,“explain”,
“to”,“a”,“computer.”,“Art”,“is”,“everything”,“else”,“we”,“do”]
maxWidth = 20
输出:
[
“Science is what we”,
“understand well”,
“enough to explain to”,
“a computer. Art is”,
“everything else we”,
"do "
]
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> ret = new ArrayList<>();
int index = 0;
while(index < words.length){
int cur = index, len = 0;
// len + words[cur].length() + cur - index 为单词之间取 一个空格的长度
while(cur < words.length && len + words[cur].length() + cur - index <= maxWidth){
// 计算纯单词长度
len = len + words[cur++].length();
}
cur--;
// System.out.println(cur + " " + len);
StringBuilder sb = new StringBuilder();
// 区分最后一行
if(cur == words.length - 1){
for(int i = index; i <= cur; i++){
sb.append(words[i]);
if(i < cur){
sb.append(' ');
}
}
}else{
int base = cur > index ? (maxWidth - len) / (cur - index) : (maxWidth - len);
String baseStr = genSpace(base);
int left = cur > index ? (maxWidth - len) % (cur - index) : 0;
String leftStr = genSpace(base + 1);
for(int i = index; i <= cur; i++){
sb.append(words[i]);
if(i < cur){
sb.append(left > 0 ? leftStr : baseStr);
left--;
}
}
}
if(sb.length() < maxWidth){
sb.append(genSpace(maxWidth - sb.length()));
}
ret.add(sb.toString());
index = cur + 1;
}
return ret;
}
private String genSpace(int n){
char[] cs = new char[n];
Arrays.fill(cs, ' ');
return new String(cs);
}
}