Long c++ code with some explanations


  • 0
    J
    class Solution {
    public:
        vector<string> fullJustify(vector<string>& words, int maxWidth) {
            vector<string> result;
            if(maxWidth==0) {
                result.push_back("");
                return result;
            }
            int i = 0, start = 0;
            while(i<words.size()) {
                //find how many words in this line;
                start = i;
                int len = 0;
                while(i<words.size() && len+words[i].size()<=maxWidth) {
                    len += words[i].size() + 1;
                    i++;
                }
                len--;
                //if i is not the end word, we insert spaces between words;
                if(i<words.size()) {
                    //corner case, if only one word in this line, we fill remianing part with white spaces;
                    if(i==start+1) {
                        string space(maxWidth-len,' ');
                        result.push_back(words[start]+space);
                    }
                    //if there are more than one word in this line, we calculate how many spaces should be inserted between words;
                    else { 
                        int spaces = (maxWidth-len)/(i-start-1);
                        int remain = (maxWidth-len)%(i-start-1);  
                        //remain is how many words from start word should be inserted with an extra space;
                        string space(spaces+1,' ');
                        string line = words[start];
                        for(int j=start+1;j<i;j++) {
                            if(j-start<=remain)
                                line += space + " " + words[j];
                            else 
                                line += space + words[j];
                        }
                        result.push_back(line);
                    }
                }
                //if i is the end word, we only do left justification and fill remaining part with spaces.
                else {
                    string line = words[start];
                    for(int j=start+1;j<i;j++)
                        line += " " + words[j];
                    string space(maxWidth-line.size(),' ');
                    result.push_back(line+space);
                }
            }
            return result;
        }
    };

Log in to reply
 

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