68. Text Justification
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. "
]
S: 细节处理
注意最后一行和只有一个单词的行的处理。多出来的空格用%处理.
注意:xxx.size()返回值是unsigned,不能与负数比较
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
int start = 0;
vector<string> result;
while (start < words.size()) {
int next = helper(words, result, start, maxWidth);
start = next;
}
return result;
}
private:
int helper(vector<string>& words, vector<string>& ans, int start, int maxWidth) {
int end = start;
int wordSize = 0;
int spaceSize = 1;
int extraSpace = 0;
string result = words[start];
for (int len = maxWidth; end < words.size() && int(words[end].size()) <= len; ++end) {
len -= (words[end].size() + 1);
wordSize += words[end].size();
}
end--;
if (end != words.size() - 1 && end != start) { //对最后一行,和只有一个单词的行的处理
spaceSize = (maxWidth - wordSize) / (end - start);
extraSpace = (maxWidth - wordSize) % (end - start);
}
string space = "";
for (int i = 0; i < spaceSize; ++i) {
space += ' ';
}
for (int i = start + 1; i <= end; ++i) {
if (extraSpace) {
result += ' ';
extraSpace--;
}
result += space + words[i];
}
for (int i = result.size(); i < maxWidth; ++i) {
result += ' ';
}
ans.push_back(result);
return end + 1;
}
};