problem:
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. " ]
本问题这道题的要求是给定一组单词和长度L,以两端对齐的方式格式化文本使每行只有L个字符,其中最后一行左对齐。每行的单词间可能需要补充额外的空格,如果空格数目不能整除单词间隔的数目,则左侧数目要多于右侧。
a、当前行只放一个单词时,空格全部在这个单词的右边
b、最后一行,单词间只有一个空格,其余空格全部在右边。然后只要贪心选择,在一行中尽可能放更多的单词。
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> result;
int wordslength = words.size();
int i,k;
for(i=0; i<wordslength; i++)
{
string s = words[i];
for(k = i+1; k<wordslength; k++)
{
string tmp = s + words[k];
if(tmp.size()+k-i > maxWidth)
break;
s += words[k];
}
int spaces = maxWidth - s.size();
int cnt = k-i;
if(cnt == 1)
{
string tmp(spaces, ' ');
s += tmp;
}
else
{
int p = i;
int sum = 0;
if(k != wordslength)
{
while(spaces)
{
int num = (int)ceil(spaces/(double)(cnt-1));
spaces -= num;
sum += words[p].size();
string tmp(num, ' ');
s = s.substr(0, sum) + tmp + s.substr(sum);
sum += num;
p++;
cnt--;
}
}
else
{
int remain = cnt - 1;
while(remain)
{
spaces--;
sum += words[p].size();
s = s.substr(0,sum)+" "+s.substr(sum);
sum+=1;
p++;
remain--;
}
string tmp(spaces, ' ');
s += tmp;
}
}
result.push_back(s);
i = k-1;
}
return result;
}
};