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 L characters.
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.
Corner Cases:
- 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.
class Solution { public: string generateOneLince(vector<string> &words, int start, int end, int L){ string s; //the line has exactly one word if(start==end){ s+=words[start]; s.append(L-words[start].size(), ' '); return s; } //the last line if(end==words.size()-1){ for(int i=start; i<=end; i++){ s+=words[i]; if(i!=end) s.append(1, ' '); } s.append(L-s.size(), ' '); return s; } //ordinary line int wordsL = 0; for(int i=start; i<=end; i++) wordsL+=words[i].size(); int aveSpace = (L-wordsL)/(end-start); int addSpace = (L-wordsL)%(end-start); for(int i=start; i<end; i++){ s+=words[i]; if(i-start<addSpace) s.append(aveSpace+1, ' '); else s.append(aveSpace, ' '); } s+=words[end]; return s; } vector<string> fullJustify(vector<string> &words, int L) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. vector<string> ret; if(words.empty() || words[0].empty() || L<=0){ string r(L, ' '); ret.push_back(r); return ret; } int start = 0; int count = 0; for(int i=0; i<words.size(); i++){ if(count+words[i].size()==L){ ret.push_back(generateOneLince(words, start, i, L)); start=i+1; count=0; } else if(count+words[i].size()>L){ ret.push_back(generateOneLince(words, start, i-1, L)); start=i; count=words[i].size()+1; } else count+=(words[i].size()+1); } if(count!=0) ret.push_back(generateOneLince(words, start, words.size()-1, L)); return ret; } };
No comments:
Post a Comment