题目如下:
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. " ]
1.每行有规定的可容纳字符数量L,
2.空格要相对均匀的分布在单词之间,可以计算出每行平均的空格数k,然后多出来的m个,从第一间隔开始每个间隔再多分配一个,即前m个间隔分配k+1个空格。
3. 最后一行相左对齐,且每个字符间隔为1个空格
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth)
{
vector<string> res;
if (words.empty())
return res;
int n = words.size();
int len = words[0].size();
int j, i = 0;
string temp;
while (i < n)
{
len = words[i].size();
//设j-1的len值小于maxWidth,加上j大于manWidth,跳出循环,j不属于此行
for (j = i + 1; j < n&&len + words[j].size() < maxWidth; j++)
{
len = len + 1 + words[j].size();
}
//到达最后一个单词,则空格k=1
if (j == n)
{
temp = allocatelastline(words, 1, i, j - 1, maxWidth);
res.push_back(temp);
break;
}
//一行只有一个单词的情况
if (j - i == 1)
{
temp = words[i];
temp.append(maxWidth - words[i].size(), ' ');
res.push_back(temp);
i = j;
continue;
}
//一般情况
int k = (maxWidth - (len - (j - i - 1))) / (j - i - 1);
int m = (maxWidth - (len - (j - i - 1))) % (j - i - 1);
temp = allocateoneline(words, k, m, i, j - 1);
res.push_back(temp);
i = j;
}
return res;
}
string allocateoneline(vector<string>&words, int k, int m, int start, int end)
{
string res;
int interval = 0;
int totalinterval = end - start;
for (int i = start; i <= end; i++)
{
res = res + words[i];
//处理间隔,只有当前有可处理间隔才处理
if (interval < totalinterval)
{
if (interval < m)
{
//前m个间隔分配k+1个空格
res.append(k + 1, ' ');
interval++;
}
else
{
//后面的间隔分配k个空格
res.append(k, ' ');
interval++;
}
}
}
return res;
}
string allocatelastline(vector<string>&words, int k, int start, int end, int maxwidth)
{
string res;
int curlength = 0;
for (int i = start; i <= end; i++)
{
res = res + words[i];
curlength = curlength + words[i].size();
if (curlength < maxwidth)
{
res = res + " ";
curlength++;
}
}
//后面空间用空格填充
res.append(maxwidth - curlength, ' ');
return res;
}
};