68 Text Justification——leetcode

68 Text Justification
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L)
    {
        if(words.empty()){
            return words;
        }
        if(L==0){
            return words;
        }
        const int N = words.size();
        int curLen=0;
        int lastLen=0;
        vector<string> ans;
        vector<string> str;
        for(int i=0;i<N;i++)
        {
            if(str.size()>0)
            {
                curLen ++;
            }
            curLen += words[i].size();

            if(curLen<=L)
            {
                str.push_back(words[i]);
                lastLen=curLen;
            }
            else
            {
                //over
                if(str.size()==1)
                {
                    string   newString = str[0];
                    if(L>str[0].size())
                    {
                        newString += string(L-str[0].size(),' ');
                    }
                    ans.push_back(newString);
                }
                else
                {
                    int tabCount = str.size()-1;
                    int q = (L-lastLen)/tabCount;
                    int r = (L-lastLen) - q*tabCount;
                    string   newString ;
                    int j=0;

                    for(;j<tabCount;j++)
                    {
                        newString += str[j];
                        if(j<r){
                            string spaces(q+2,' ');
                            newString += spaces;
                        }
                        else {
                            string spaces(q+1,' ');
                            newString += spaces;
                        }
                    }
                    newString += str[j];
                    ans.push_back(newString);
                }
                str.clear();
                str.push_back(words[i]);
                lastLen = curLen = words[i].size();
            }
        }

        if(str.size()==1)
        {
            string   newString = str[0];
            if(L>str[0].size())
            {
                newString += string(L-str[0].size(),' ');
            }
            ans.push_back(newString);
        }
        else
        {
            int tabCount = str.size()-1;
            string   newString ;
            int j=0;
            int len=0;
            for(;j<tabCount;j++)
            {
                newString += str[j];
                newString +=" ";
                len+=str[j].size()+1;
            }
            newString += str[j];
            len += str[j].size();
            newString += string(L-len,' ');
            ans.push_back(newString);
        }
        return ans;
    }
};

这题,其实没啥可说的,需要的是细心,这个是常见的阅读器排版问题。嗯,错过很多次,慢慢修改就对了。

猜你喜欢

转载自lvdccyb.iteye.com/blog/2201364