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 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.
class Solution { public: vector<string> fullJustify(vector<string> &words, int L) { // Start typing your C/C++ solution below // DO NOT write int main() function int cur_length = 0; vector<string> result; vector<string> line_words; for (int i = 0; i < words.size(); ++i) { if (cur_length + words[i].size() <= L) { cur_length += words[i].size() + 1; line_words.push_back(words[i]); if (i == words.size() - 1) { string line; int cnt = L; for (int j = 0 ; j < line_words.size(); ++j) { line.append(line_words[j]); cnt -= line_words[j].size(); if (cnt > 0) { line.append(" "); --cnt; } } line.append(string(cnt, ' ')); result.push_back(line); } } else { result.push_back(edit_string(line_words, cur_length, L)); --i; } } return result; } string edit_string(vector<string> &line_words, int& cur_length, int L) { string line; int n_gap = line_words.size() - 1; int space = L - cur_length + line_words.size(); if (n_gap == 0) { line.append(line_words[0]); line.append(string(space, ' ')); } else { int gap = space / n_gap; int more = space % n_gap; for (int j = 0; j < line_words.size(); ++j) { line.append(line_words[j]); string blank; if (j < more) { blank = string(gap + 1, ' '); } else { blank = string(gap, ' '); } if (line.size() < L) { line.append(blank); } } } cur_length = 0; line_words.clear(); return line; } };