leetcode 68: Text Justification

来源:互联网 发布:sql where like 多字段 编辑:程序博客网 时间:2024/04/28 19:52
class Solution {public:    vector<string> fullJustify(vector<string>& words, int maxWidth) {        int i,j;        int width=0;        vector<string> res;        if(words[0].empty())        {            string s="";            for(int x=0;x<maxWidth;x++)                s+=' ';            res.push_back(s);            return res;        }        for(i=0,j=i;j<=words.size();j++)        {            if(j==words.size()||width+words[j].size()+j-i>maxWidth)            {                int num_space=maxWidth-width;//number of space to be added                int num_slot=j-i-1;//number of slots between a line of words                string s;                if(j-i==1)//a line can only fit one word                {                    s+=words[i];                    for(int x=0;x<num_space;x++)                        s+=' ';                }                else if(j==words.size())//reaches the last word                {                    for(int x=i;x<j;x++)                        s+=words[x]+' ';                    for(int x=0;x<num_space-(j-i);x++)                        s+=' ';                }                else//length of words can fit maxWidth                {                    string slot;                    for(int x=0;x<num_space/num_slot;x++)                        slot+=' ';                    s+=words[i];                    int rem=num_space%num_slot;                    for(int x=i+1;x<j;x++)                    {                        s+=slot;                        if(rem)                        {                            s+=' ';                            rem--;                        }                        s+=words[x];                    }                }                res.push_back(s);                width=0;                i=j;            }            if(j<words.size())                width+=words[j].size();        }        return res;    }};

0 0
原创粉丝点击