classSolution {public:vector<string> fullJustify(vector<string>& words,int maxWidth) { vector<string> res; // Let i to i+k-1 words be put in the same sentence // use l to record current length of words and corresponding spacesint k, l;for(int i=0; i<words.size(); i+=k) { // Determine how many words can we put in this sentencefor(k=l=0; i+k<words.size() && l+words[i+k].length()<=maxWidth-k; k++) { l +=words[i+k].size(); } // Starting putting words into current sentence string tmp =words[i];for(int j =0; j < k -1; j++) { // This line of code is for last line // E.g. the last line is "shall be " // instead of "shall be", // because the last line must be left-justified.if(i + k >=words.size()) tmp +=" "; // Distribute space evenly by (maxWidth - l) / (k - 1) // if there are more spaces which cannot be distributed evenly // We can know how many more spaces need to be put by (maxWidth - l) % (k - 1) // then if j < (maxWidth - l) % (k - 1), we need to put one more spaceelse tmp +=string((maxWidth - l) / (k -1) + (j < (maxWidth - l) % (k -1)),' '); tmp +=words[i+j+1]; } // Put spaces if tmp is not as long as maxWidth tmp +=string(maxWidth -tmp.size(),' '); // Push current sentence into answerres.push_back(tmp); }return res; }};