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.
先将单词分离出来,然后分别记录每一行可以存多少个单词,然后对于非最后一行,根据要求求出每个单词之间的空格数,对于最后一行则是每个单词间隔一个空格,但需要记得在最后一个单词之后补齐空格。
代码如下:
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
int k=0,l=0,j=0;
vector<string> result;
for(int i=0;i<words.size();i += k)
{
for(k=0,l=0;i+k<words.size()&&l+words[i+k].size()<=maxWidth-k;k++)
{
l += words[i+k].size();
}
string temp="";
for(j=0;j<k-1;j++)
{
temp += words[i+j];
if(i+k >= words.size())
temp += " ";
else
temp += string((maxWidth-l)/(k-1)+(j<(maxWidth-l)%(k-1)),' ');
}
temp += words[i+k-1];
temp += string(maxWidth-temp.size(),' ');
result.push_back(temp);
}
return result;
}
};
本文介绍了一个文本排版算法,该算法能够将给定的一组单词按照指定长度进行排版,确保每行文字达到完全左右对齐的效果。文章详细解释了算法的工作原理,包括如何计算每行可容纳的单词数量、如何均匀分布额外的空白字符等。
321

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



