Given an array of words and a length L, format the text such, all line have exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; That's, pack as many words as you can on each line. Pad extra spaces when necessary so, each line has ‘ ‘ exactlyL characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left would be assigned more SP Aces than the slots on the right.
For the last line of text, it should being justified and no extra space is inserted between words.
For example,
Words["This", "is", "an", "example", "of", "text", "justification."]
L: 16 .
Return the formatted lines as:
[ "This was an", "example of text", " justification. "]
Note:each word is guaranteed isn't to exceed L in length.
Consider a variety of special situations and how to make the free space distribution as average as possible. CNT is used to record the number of words in the current line, and Len is used to record the length of the current word. Note that you want to execute i--after you finish processing a line, or the program skips the first POS line. A For each gap evenly allocated to the number of spaces, B is not divisible and the remaining number of spaces, the B is assigned to the first B gap on the line.
1 classSolution {2 Public:3vector<string> fulljustify (vector<string> &words,intL) {4vector<string>Res;5 strings;6 intpos =0, cnt =0;7 intLen =0;8 intA, B, C;9 for(inti =0; I < words.size (); ++i) {Ten if(Len + words[i].length () + CNT <=L) { One++CNT; ALen + =words[i].length (); -}Else { -s + =Words[pos]; the if(CNT = =1) { -c = L-Len; - for(intK =0; K < C; ++k) -s + =' '; +}Else { -A = (L-len)/(CNT-1); +b = (L-len)% (CNT-1); A for(intj =1; J < CNT; ++j) { atc =A; - if(J <= B) + +C; - for(intK =0; K < C; ++k) -s + =' '; -s + = words[pos+j]; - } in } - Res.push_back (s); to s.clear (); +pos = i--; -CNT =0; theLen =0; * } $ }Panax Notoginsengs + =Words[pos]; - for(intj =1; J < CNT; ++j) { thes = s +' '+ Words[pos +j]; + } Ac = l-len-cnt +1; the for(intK =0; K < C; ++k) { +s + =' '; - } $ Res.push_back (s); $ returnRes; - } -};
[Leetcode] Text justification