[Leetcode] Text Justification

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.