题目:
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 exactlyL 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.
- 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.
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) {
vector<string> ans;
int beg = 0;
while (beg < words.size()) {
int i = beg;
int wordCnt = 0, total = 0;
string s;
for (; i < words.size(); i++) {
if (total <= L) {
if (wordCnt == 0)
total += words[i].size();
else
total += words[i].size() + 1;
wordCnt++;
if (total > L)
break;
}
}
if (total > L) {
total -= (words[i].size()+1);
wordCnt--;
}
//对每行进行处理,每行只有一个单词
if (wordCnt == 1) {
int space = L - total;
s.insert(s.begin(), words[beg].begin(), words[beg].end());
s.insert(s.end(), space, ' ');
}
//最后一行特殊处理
else if (i == words.size()) {
int space = L - total;
s.insert(s.begin(), words[beg].begin(), words[beg].end());
for (int j = beg + 1; j < beg + wordCnt; j++) {
s.insert(s.end(), 1, ' ');
s.insert(s.end(), words[j].begin(), words[j].end());
}
s.insert(s.end(), space, ' ');
}
else {
int space2 = (L - total) / (wordCnt - 1);
//前pre个的空格为space1个,之后的空格为space2
int pre = (L - total) % (wordCnt - 1);
int space1 = space2 + 1;
s.insert(s.begin(), words[beg].begin(), words[beg].end());
for (int j = beg + 1; j < beg + wordCnt; j++) {
//插入空格
if (pre > 0) {
s.insert(s.end(), space1+1, ' ');
pre--;
}
else
s.insert(s.end(), space2+1, ' ');
s.insert(s.end(), words[j].begin(), words[j].end());
}
}
ans.push_back(s);
beg = i;
}
return ans;
}
};