Sharing my 0ms C++ solution


  • 0
    T
    class Solution {
    public:
        vector<string> fullJustify(vector<string>& words, int maxWidth) {
            int n = words.size();
            vector<string> result;
            int index=0;
            string s;
            vector<int> spaceSizes;
            int len, wordsLen, i, icount;
     
            while(index<n)
            {
                s = words[index];
                len = words[index].length();
                wordsLen = words[index].length();
                i=index;
                while(i+1<n && len+1+words[i+1].length()<=maxWidth)
                {
                    len = len+1+words[i+1].length();
                    wordsLen = wordsLen + words[i+1].length();
                    i++;
                }
                
                if(i>index && i<n-1)
                {
                    spaceSizes.resize(i-index, 0);
                    for(int j=0; j<spaceSizes.size(); j++)
                        spaceSizes[j] = 0;
    
                    for(icount=0; icount<(maxWidth-wordsLen); icount++)
                        spaceSizes[icount%(i-index)]++;
                    
                    for(icount=index+1; icount<=i; icount++)
                        if(spaceSizes[icount-index-1]>0)
                            s = s + string(spaceSizes[icount-index-1], ' ') + words[icount];
                            
                    result.push_back(s);
                    index = 1 + i;
                }
                else
                {   
                    for(icount=index+1; icount<=i; icount++)
                        s = s + ' ' + words[icount];
                    s = s + string(maxWidth-len, ' ');
                    result.push_back(s);
                    index = i + 1;
                }
            }
            
            return result;
        }
    };

Log in to reply
 

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