Title Link: https://leetcode.com/problems/text-justification/
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 ‘ ‘
exactly L 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 was guaranteed not to exceed L in length.
Idea: is a string processing of the topic, not difficult, but it is difficult to write more elegant.
Two code as follows, the first one is my own, the code is longer, 0ms. The second one is the reference of others, 4ms, but more beautiful.
The second method is very clever to find the unbalanced space, is to use the position and the remainder of the relationship to the left to allocate extra space.
The code is as follows:
Class Solution {public:vector<string> Fulljustify (vector<string>& words, int maxWidth) {int cn t = 0, left = 0; vector<string> result; for (int i =0; i< words.size (); i++) {cnt + = words[i].size (); if (Cnt+i-left > MaxWidth | | i+1==words.size ()) {if (Cnt+i-left > MaxWidth) cnt-= words[i- -].size (); String str = Words[left]; for (int j = left+1; j<= i; j + +) {int m = maxwidth-cnt, n = i-left; if (i+1==words.size ()) str + = ""; else Str.append (m/n + (j-left-1<m% n), "); str + = Words[j]; } str.append (Maxwidth-str.size (), "); Result.push_back (str); left = i+1, cnt = 0; }} return result; }};
Class Solution {public: vector<string> fulljustify (vector<string>& words, int maxWidth) { vector<string> result; for (int i=0, m, N; i< words.size (); i+=m) {for (M=0,n=0;i+m<words.size () &&m+n+words[i+m].size ( ) <=maxWidth; m++) n+= words[i+m].size (); String str = words[i]; for (int j = 0; J < M-1; J + +) { if (i+m >= words.size ()) str+= ""; else Str.append ((maxwidth-n)/(m-1) + (j< (maxwidth-n)% (m-1)), '); str + = words[i+j+1]; } Str.append (Maxwidth-str.size (), '); Result.push_back (str); } return result;} ;
Second type of reference: Https://leetcode.com/discuss/13610/share-my-concise-c-solution-less-than-20-lines
[Leetcode] 68. Text Justification Problem Solving report