The key to this problem are to identify all the words so can be added to a line and then identify the places that require An additional space (for the spaces as even as possible, we can only add a additional space if needed). This link had a brilliant solution that have a nice formula for the places that require a addtional space. The code is written as follows.
1 classSolution {2 Public:3vector<string> fulljustify (vector<string>& words,intmaxWidth) {4 intIDX =0, n =words.size ();5vector<string>justifications;6 while(IDX <N) {7 intwidth =0, numwords =0;8 while(idx + numwords < n && width + words[idx + numwords].length () <= maxWidth-numwords) {9Width + = Words[idx +numwords].length ();Tennumwords++; One } A stringJustification =Words[idx]; - for(intj =0; J < Numwords-1; J + +) { - if(idx + numwords = = N) Justification + =" "; the ElseJustification + =string((maxwidth-width)/(Numwords-1) + (J < (maxwidth-width)% (Numwords-1)),' '); -Justification + = Words[idx + j +1]; - } -Justification + =string(Maxwidth-justification.length (),' '); + Justifications.push_back (justification); -IDX + =numwords; + } A returnjustifications; at } -};
[Leetcode] Text Justification