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. " ]
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.
vector<string> fullJustify(vector<string> &words, int L) {
// Note: The Solution object is instantiated only once.
vector<string> res;
if(words.size() < 1){
string tmp = "";
res.push_back(tmp);
return res;
}
int pword = 0;
while(pword < words.size())
{
int len = words[pword].size();
int pbegin = pword;
while((pword + 1 < words.size()) && (len + pword - pbegin < L))
{
pword++;
len += words[pword].size();
}
if(len + pword - pbegin > L)
{
len -= words[pword].size();
pword--;
}
string tmp = "";
if(pbegin == pword){
tmp = words[pbegin];
int spacenum = L-len;
while(spacenum--)
tmp += ' ';
}else{
if(pword == words.size()-1)
{
while(pbegin < pword)
tmp += words[pbegin++] + ' ';
tmp += words[pbegin];
if(tmp.size() < L)
{
int spacenum = L-tmp.size();
while(spacenum--)
tmp += ' ';
}
}else{
int samespace = (L - len)/(pword - pbegin);
int otherspace = (L - len)%(pword - pbegin);
while(pbegin < pword)
{
int spacenum = samespace;
if(otherspace>0)
{
otherspace--;
spacenum++;
}
tmp += words[pbegin++];
while(spacenum--)
tmp += ' ';
}
tmp += words[pbegin];
}
}
res.push_back(tmp);
pword++;
}
return res;
}

本文介绍了一种将文本格式化为完全对齐的算法,确保每行字符数固定,并均匀分布单词间的空格。该算法考虑了不同情况,如最后一行的左对齐处理以及当一行只有一个单词时的情况。

512

被折叠的 条评论
为什么被折叠?



