Question
我觉得还是翻译一下好
给一个字符串数组,一个L整数
1、一行最多有L个字符
2、把这些字符串尽可能多得放在一行
3、每个字符串之间都有空格分开
4、字符串之间空格的个数平均分配,如果不能除尽,那么左边的空格数大于右边的
5、最后一行字符串左对齐,之间以一个空格分隔,剩余用空格补齐
Tips
No way, just let it be complex : )
Code
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> res;
string tmp;
int vSize = words.size();
if(vSize==0)
res.push_back(string(maxWidth,' '));
else{
if(words[0].length()==0){ //words[0]=""的时候
res.push_back(string(maxWidth,' '));
return res;
}
}
int pos=0; //当前已寻找过的字符串位置
while(pos<vSize){
tmp.clear();
int count=0; //计算出当前位置之后可以有几个字符串添加到本行
int len=0; //计算可以添加到本行的字符串长度
bool flag = false; //用来区别最后一位是“ ”(未完成),和已完成状态
while(true){
if(flag){
//cout<<tmp<<endl;
res.push_back(tmp);
break;
}
if(pos+count==vSize){ //最后一行
for(int i=0;i<count;++i){
tmp+=words[pos+i]+" ";
}
tmp+=string(maxWidth-tmp.length(),' ');
flag = true;
}else if((len+=words[pos+count].length())>maxWidth){ //当前字符串不能用在其中
int blankCount = maxWidth, restBlank = 0;
for(int i=0;i<count;++i)
blankCount-=words[pos+i].length();
if(count!=1){
restBlank = blankCount%(count-1); //除不尽
//cout<<"restBlank:"<<restBlank<<endl;
blankCount=blankCount/(count-1); //每个间隔必须存在的空格数
}
string blank(blankCount,' ');
//cout<<'-'<<blank<<'-'<<endl; //这里空格字符串的初始化有问题
//cout<<"blankCount:"<<blankCount<<endl
// <<"blank length:"<<blank.length()<<endl;
for(int i=0;i<count;++i){
if(restBlank == 0)
tmp+=words[pos+i]+blank;
else{
tmp+=words[pos+i]+blank+" ";
--restBlank;
}
//cout<<"tmp:-"<<tmp<<'-'<<endl;
}
if(count!=1)
tmp.erase(tmp.end()-blankCount,tmp.end());
//cout<<tmp<<endl;
len = maxWidth;
flag = true;
}else if(len==maxWidth){ //正好一个单词一个空地填满
string blank=" ";
for(int i=0;i<=count;++i)
tmp+=words[pos+i]+blank;
tmp.erase(tmp.end()-1,tmp.end());
len = maxWidth;
flag = true;
++count;
}else{
len+=1; //表示暂时加一个‘ ’
++count;
}
}
pos = pos+count;
}
return res;
}
};