| 68 | Text Justification |
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L)
{
if(words.empty()){
return words;
}
if(L==0){
return words;
}
const int N = words.size();
int curLen=0;
int lastLen=0;
vector<string> ans;
vector<string> str;
for(int i=0;i<N;i++)
{
if(str.size()>0)
{
curLen ++;
}
curLen += words[i].size();
if(curLen<=L)
{
str.push_back(words[i]);
lastLen=curLen;
}
else
{
//over
if(str.size()==1)
{
string newString = str[0];
if(L>str[0].size())
{
newString += string(L-str[0].size(),' ');
}
ans.push_back(newString);
}
else
{
int tabCount = str.size()-1;
int q = (L-lastLen)/tabCount;
int r = (L-lastLen) - q*tabCount;
string newString ;
int j=0;
for(;j<tabCount;j++)
{
newString += str[j];
if(j<r){
string spaces(q+2,' ');
newString += spaces;
}
else {
string spaces(q+1,' ');
newString += spaces;
}
}
newString += str[j];
ans.push_back(newString);
}
str.clear();
str.push_back(words[i]);
lastLen = curLen = words[i].size();
}
}
if(str.size()==1)
{
string newString = str[0];
if(L>str[0].size())
{
newString += string(L-str[0].size(),' ');
}
ans.push_back(newString);
}
else
{
int tabCount = str.size()-1;
string newString ;
int j=0;
int len=0;
for(;j<tabCount;j++)
{
newString += str[j];
newString +=" ";
len+=str[j].size()+1;
}
newString += str[j];
len += str[j].size();
newString += string(L-len,' ');
ans.push_back(newString);
}
return ans;
}
};
这题,其实没啥可说的,需要的是细心,这个是常见的阅读器排版问题。嗯,错过很多次,慢慢修改就对了。

本文提供了一种解决文本排版问题的算法实现,通过合理的字符间距调整,使得文本在限定宽度内均匀分布,同时考虑了最后一行左对齐的特殊情况。
573

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



