标签:style blog http color io os ar for sp
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.
class Solution { public: vector<string> fullJustify(vector<string> &words, int L) { vector<string> result; if(words.size() == 1 && words[0] == ""){ result.push_back(string(L,‘ ‘)); return result; } vector<string>::iterator l_start = words.begin(); int cur_len = 0; int word_count = 0; for(auto i = words.begin(); i != words.end(); i++){ cur_len += i->length(); word_count++; if(i == prev(words.end()) && cur_len+word_count-1 <= L){ string tmp; for(vector<string>::iterator j = l_start; j != words.end(); j++) tmp.append(*j+" "); tmp.pop_back(); if(cur_len + word_count - 1 < L) tmp.append(string(L-cur_len-word_count+1, ‘ ‘)); result.push_back(tmp); return result; } if(cur_len+word_count-1 == L){ string tmp; tmp.append(*l_start); for(vector<string>::iterator j = next(l_start); j != next(i); j++){ tmp.append(" "); tmp.append(*j); } result.push_back(tmp); l_start = next(i); cur_len = 0; word_count = 0; }else if(cur_len+word_count-1 > L){ cur_len -= i->length(); word_count--; int residue = (word_count > 1)?(L-cur_len)%(word_count-1):0; int quotient = (word_count > 1)?(L-cur_len)/(word_count-1):(L-cur_len); int add = 0; if(residue != 0) add = 1; string tmp; tmp.append(*l_start); tmp.append(string(add+quotient,‘ ‘)); residue--; if(l_start != prev(i)){ for(vector<string>::iterator j = next(l_start); j != prev(i); j++){ tmp.append(*j); if(residue > 0){ tmp.append(string(add+quotient,‘ ‘)); residue--; }else tmp.append(string(quotient, ‘ ‘)); } tmp.append(*prev(i)); } result.push_back(tmp); l_start = i; i--; cur_len = 0; word_count = 0; } } return result; } };
标签:style blog http color io os ar for sp
原文地址:http://www.cnblogs.com/Kai-Xing/p/4052169.html