68. Text Justification
Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth 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 maxWidth 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.
Note:
A word is defined as a character sequence consisting of non-space characters only.
Each word’s length is guaranteed to be greater than 0 and not exceed maxWidth.
The input array words contains at least one word.
Example 1:
Input:
words = [“This”, “is”, “an”, “example”, “of”, “text”, “justification.”]
maxWidth = 16
Output:
[
“This is an”,
“example of text”,
"justification. "
]
Example 2:
Input:
words = [“What”,“must”,“be”,“acknowledgment”,“shall”,“be”]
maxWidth = 16
Output:
[
“What must be”,
"acknowledgment ",
"shall be "
]
Explanation: Note that the last line is "shall be " instead of “shall be”,
because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified becase it contains only one word.
Example 3:
Input:
words = [“Science”,“is”,“what”,“we”,“understand”,“well”,“enough”,“to”,“explain”,
“to”,“a”,“computer.”,“Art”,“is”,“everything”,“else”,“we”,“do”]
maxWidth = 20
Output:
[
“Science is what we”,
“understand well”,
“enough to explain to”,
“a computer. Art is”,
“everything else we”,
"do "
]
Approach
题目大意:这是一道模拟题,模拟居中对齐和左对齐,不是很好模拟,需要细心。
解题思路:首先我们尝试每个单词之间空一个格,不断累加单词,当然在加的之前就要判断是否会超出了它给定的范围,如果会超出,则就不用再进行累加了,开始对齐,我们把多余的空格均匀平坦给前面每个单词之间里,当然这个多余的空格不一定能够均匀平坦,那就继续把余数从左到右给每两个单词加一,这样就满足题目不能绝对公平的时候,就要求的左边的空格要比右边多(例如空格数为 3,3,2,2,而不能4,3,2,1)
Code
class Solution {
public:
vector<string> fullJustify(vector<string> words, int maxWidth) {
int i = 0;
vector<string> ans;
while (i < words.size()) {
i = justify(words, i, ans, maxWidth);
}
return ans;
}
int justify(vector<string> &words, int pos, vector<string> &ans, const int &maxWidth) {
int cnt = 1, width = words[pos].size(), i = pos + 1, l = 0, wid = 1, c = 0;
string res(maxWidth, ' ');
while (i < words.size()) {
if (width + wid + words[i].size() <= maxWidth) {
cnt++;
width = width + wid + words[i].size();
} else {
if (cnt <= 2) {
for (auto s:words[pos]) {
res[l++] = s;
}
if (--cnt) {
l = maxWidth - 1;
for (int j = words[pos + 1].size() - 1; j >= 0; j--) {
res[l--] = words[pos + 1][j];
}
}
goto back;
}
int space = maxWidth - width;
int gap = space / (cnt - 1);
wid += gap;
c = space % (cnt - 1);
goto to;
}
i++;
}
to:
for (int j = pos; j < i; j++) {
for (auto s:words[j]) {
res[l++] = s;
}
l += wid;
if (c) {
l++, c--;
}
}
back:
ans.push_back(res);
return i;
}
};