68. Text Justification

来源:互联网 发布:大疆无人机香港知乎 编辑:程序博客网 时间:2024/06/05 08:02

1.最后一行的处理与前面不一样

2.空格需要均匀分布

class Solution {public:    vector<string> fullJustify(vector<string>& words, int maxWidth) {        int n=words.size();        vector<string> ans;        int i,j;        int cur=0;        int num=0;        for(i=0;i<n;i+=num)        {            cur=0;            num=0;            int space=0;            string tmp="";            for(j=i;j<n;j++)            {                cur+=words[j].size();                num++;                if(cur+num-1>maxWidth)                    break;            }            if(cur+num-1>maxWidth)            {                cur-=words[j].size();                num--;            }                        if(j>=n)            {                for(j=i;j<i+num-1;j++)                {                    words[j]+=' ';                    tmp+=words[j];                }                tmp+=words[j];                int len=tmp.size();                for(j=0;j<maxWidth-len;j++)                    tmp+=' ';            }                        else            {                space=maxWidth-cur;                while(space)                {                    if(num==1)                    {                        words[i]+=' ';                        space--;                    }                    for(j=i;j<i+num-1&&space;j++)                    {                        words[j]+=' ';                        space--;                    }                }                for(j=i;j<i+num;j++)                    tmp+=words[j];            }                        ans.push_back(tmp);                    }        return ans;    }};


0 0