C++ 2ms solution


  • 0
    P
    class Solution {
    public:
        vector<string> fullJustify(vector<string> &words, int L) {
            vector<string> res;
            int cl(-1), wc(0), n(words.size());
            for (int i=0; i<n; ++i)
            {
                if (cl+1+words[i].size()<=L)
                {
                    cl+=1+words[i].size();
                    ++wc;
                }
                else
                {
                    string rp(words[i-wc]);
                    if (wc!=1)
                    {
                        int nsp((L-cl+wc-1)/(wc-1)), addsp((L-cl+wc-1)%(wc-1));
                        for (int j=i-wc+1; j<i; ++j)
                        {
                            for (int k=0; k<nsp; ++k) rp+=' ';
                            if (addsp-->0) rp+=' ';
                            rp+=words[j];
                        }
                    }
                    while (rp.size()<L) rp+=' ';
                    res.push_back(rp);
                    cl=words[i].size();
                    wc=1;
                }
            }
            string rp=words[n-wc];
            if (wc!=1)
            {
                for (int j=n-wc+1; j<n; ++j)
                    rp+=" "+words[j];
            }
            while (rp.size()<L) rp+=' ';
            res.push_back(rp);
            return res;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.