您的位置:首页 > 其它

68. Text Justification *HARD*

2016-03-13 11:57 274 查看
GivenanarrayofwordsandalengthL,formatthetextsuchthateachlinehasexactlyLcharactersandisfully(leftandright)justified.

Youshouldpackyourwordsinagreedyapproach;thatis,packasmanywordsasyoucanineachline.Padextraspaces
''
whennecessarysothateachlinehasexactlyLcharacters.

Extraspacesbetweenwordsshouldbedistributedasevenlyaspossible.Ifthenumberofspacesonalinedonotdivideevenlybetweenwords,theemptyslotsontheleftwillbeassignedmorespacesthantheslotsontheright.

Forthelastlineoftext,itshouldbeleftjustifiedandnoextraspaceisinsertedbetweenwords.

Forexample,
words:
["This","is","an","example","of","text","justification."]

L:
16
.

Returntheformattedlinesas:

[
"Thisisan",
"exampleoftext",
"justification."
]


Note:EachwordisguaranteednottoexceedLinlength.

clicktoshowcornercases.

CornerCases:

Alineotherthanthelastlinemightcontainonlyoneword.Whatshouldyoudointhiscase?
Inthiscase,thatlineshouldbeleft-justified.

classSolution{
public:
vector<string>fullJustify(vector<string>&words,intmaxWidth){
intn=words.size(),l,extra,eachex,i,j,k,t;
vector<int>len(n,0);
for(i=0;i<n;i++)
len[i]=words[i].length();
vector<string>ans;
i=0;
while(i<n)
{
for(l=len[i],j=i+1;j<n&&l<=maxWidth;j++)
l+=len[j]+1;
strings=words[i];
if(j==n&&l<=maxWidth)//thelastline
{
for(k=i+1;k<j;k++)
{
s+='';
s+=words[k];
}
}
else
{
j--;
l-=len[j]+1;
extra=maxWidth-l;
eachex=(j>i+1)?extra/(j-i-1):extra;
for(k=i+1;k<j;k++)
{
if(extra)
{
if((j==i)||(extra==eachex*(j-k)))
{
for(t=0;t<eachex;t++)
s+='';
extra-=eachex;
}
else
{
for(t=0;t<eachex+1;t++)
s+='';
extra-=eachex+1;
}

}
s+='';
s+=words[k];
}
}
for(k=s.length();k<maxWidth;k++)
s+='';
ans.push_back(s);
i=j;
}
returnans;
}
};


测试用例:

["a","b","c","d","e"]1--["a","b","c","d","e"]

["Listen","to","many,","speak","to","a","few."]6--["Listen","to","many,","speak","toa","few."]
["Here","is","an","example","of","text","justification."]16--
["Hereisan","exampleoftext","justification."]

["Don't","go","around","saying","the","world","owes","you","a","living;","the","world","owes","you","nothing;","it","was","here","first."]
30--

["Don'tgoaroundsayingthe","worldowesyoualiving;the","worldowesyounothing;itwas","herefirst."]


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: