Can anybody help me for my code? It was thrown to runtime error. But the code works on my own laptop.


  • 0
    K
    class Solution {
    public:
        string convert(vector<string>& words, int start, int last, int maxWidth );
        vector<string> fullJustify(vector<string>& words, int maxWidth);
    };
    
    string Solution::convert(vector<string>& words, int start, int last, int maxWidth )
    {
        if ( start == last ){
            int len = (int) words[start].size();
            return words[start] + string( maxWidth-len, ' ' );
        }
        int wordsLen = 0;
        for ( int i = start; i <= last; i++ )
            wordsLen += (int) words[i].size();
        int d = (maxWidth - wordsLen) / (last - start);
        int r = (maxWidth - wordsLen) % (last - start);
        string ret = "";
        for ( int i = start; i < last; i++ ){
            ret += words[i];
            ret += string(d,' ');
            if ( i < r + start ) ret += " ";
        }
        ret += words[last];
        return ret;
    }
    
    vector<string> Solution::fullJustify(vector<string>& words, int maxWidth)
    {
        vector<string> ret;
        int len = (int) words.size();
        if ( len == 1 ) return vector<string>(1, words[0]);
        
        int i = 0; int j; int lenj; int tmpLen;
        while ( i < len ){
            j = i;
            tmpLen = 0; lenj = (int) words[j].size();
            while ( tmpLen + lenj + 1 <= maxWidth + 1 && j < len ){
                tmpLen += (lenj + 1);
                j++;
                lenj = (int) words[j].size();
            }
            j--;
            string s = convert(words, i, j, maxWidth);
            ret.push_back(s);
            i = j+1;
        }
        return ret;
    }

Log in to reply
 

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