没有意思的字符串模拟题
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> latest;
vector<vector<int>> result;
vector<int> ans;
int num=0;
for(int i=0;i<words.size();i++)
{
if(num==0){
num+=words[i].length();
}
else
num+=words[i].length()+1;
if(num==maxWidth)
{
ans.push_back(i);
result.push_back(ans);
ans.clear();
num=0;
}
else if(num>maxWidth)
{
result.push_back(ans);
ans.clear();
ans.push_back(i);
num=0;
num+=words[i].length();
}
else
{
ans.push_back(i);
}
}
if(ans.size()!=0)
{
result.push_back(ans);
}
string str="";
for(int i=0;i<result.size();i++)
{
if(i==result.size()-1)
{
str="";
str+=words[result[i][0]];
for(int j=1;j<result[i].size();j++)
{
str+=" ";
str+=words[result[i][j]];
}
int l=str.length();
for(int k=0;k<maxWidth-l;k++)
{
str+=" ";
}
latest.push_back(str);
break;
}
str="";
int sum=0;
int len=result[i].size();
for(int j=0;j<result[i].size();j++)
{
sum+=words[result[i][j]].length();
}
int s = maxWidth-sum;
int av=0;
int sb=0;
if(len!=1){
av = s/(len-1);
sb = s%(len-1);
}
str+=words[result[i][0]];
for(int j=1;j<result[i].size();j++)
{
for(int k=0;k<av;k++)
{
str+=" ";
}
if(sb>0)
{
str+=" ";
sb--;
}
str+=words[result[i][j]];
}
if(len==1)
{
int l=str.length();
for(int k=0;k<maxWidth-l;k++)
{
str+=" ";
}
}
latest.push_back(str);
}
return latest;
}
};