[LeetCode] 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 exactlyL 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.
- 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.
String
class Solution { public: vector<string> fullJustify(vector<string> &words, int L) { words.push_back(string(L, 'a')); size_t n = words.size(); int len = 0; bool isFirst = true; vector<string> res; int start = 0, end = 0; int remainder = 0; string str; for(int i = 0; i < n; i++) { if(isFirst) { isFirst = false; len = words[i].size(); start = i; //cout << "start\t" << start << endl; } else { if(words[i].size() + 1 + len <= L) len += words[i].size() + 1; else { end = i - 1; remainder = L - len; if(start == end) // only one world { str = words[start]; for(int j = 0; j < remainder; j++) str += ' '; res.push_back(str); isFirst = true; str.clear(); len = 0; i--; //handle from the start begin; continue; } //cout << "start\t" << start << endl; //cout << "end\t" << end << endl; //cout << "n\t" << n<< endl; if(end == n-2) // the last line { for(int j = start; j <= end; j++) { if(j == start) str += words[j]; else str += ' ' + words[j]; } for(int j = 0; j < remainder; j++) str += ' '; } else { int average = remainder/(end - start ); remainder = remainder%(end - start ); for(int j = start; j <= end; j++) { if(j == start) str += words[j]; else { int tmp = average; while(tmp > 0) { str += ' '; tmp--; } if(remainder > 0) { str += ' '; remainder --; } str += ' '; str += words[j]; } } } //cout << "str:" << str<< endl; res.push_back(str); isFirst = true; str.clear(); len = 0; i--; //handle from the start begin; } } //cout << "len\t" << len<< endl; } return res; } };