Text Justification
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' '
when necessary so that each line has exactly Lcharacters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left 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 is an", "example of text", "justification. " ]
Note: Each word is guaranteed not to exceed L in length.
- A line other than the last line might contain only one word. What should you do in this case?
In this case, that line should be left-justified.
' '
when necessary so that each line has exactly Lcharacters. 那么我们每一行我们在保证单词总字符数加空格数小于等于L的条件下,pad最多的单词。class Solution { public: vector<string> fullJustify(vector<string> &words, int L) { vector<string> res; if(words.size() == 0) return res; int line = 0; for(vector<string>::iterator start = words.begin(); start != words.end(); ){ line++; vector<string>::iterator end = next(start); int cur_len = start->length(); int cur_num = 1; while(end != words.end() && cur_len + end->length() + cur_num <= L){ cur_len += end->length(); cur_num++; end++; } //only one line or not to the end if(line == 1 || end != words.end()){ int quotient = (cur_num == 1)?0:(L-cur_len)/(cur_num-1); int residue = (cur_num == 1)?(L-cur_len):(L-cur_len)%(cur_num-1); string tmp; for(vector<string>::iterator p = start; p != end; p++){ tmp.append(*p); if(next(p) != end){ int space_n = (residue > 0)?1:0; tmp.append(string(quotient+space_n, ' ')); residue--; }else if(cur_num == 1){ tmp.append(string(residue, ' ')); } } res.push_back(tmp); }else{//not the first line and to the end string tmp; for(vector<string>::iterator p = start; p != end; p++){ tmp.append(*p); if(next(p) != end){ tmp.push_back(' '); } } if(L-cur_len-cur_num+1 > 0)tmp.append(string(L-cur_len-cur_num+1, ' ')); res.push_back(tmp); } start = end; } return res; } };