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.
- 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(object): def fullJustify(self, words, maxWidth): """ :type words: List[str] :type maxWidth: int :rtype: List[str] """ #slice the words in a sequential way, don't understand the last line meaning if not words: return [] res = [] n = len(words) start = 0 while start < n: lengthSum = 0 cnt = 0 while start+cnt < n and lengthSum + len(words[start+cnt]) + cnt <= maxWidth: #frist test whether can add the word, then add the word in the line lengthSum += len(words[start+cnt]) cnt += 1 #make the line if cnt == 1: res.append(words[start]+(maxWidth-lengthSum)*" ") elif start + cnt == n: #the last line, several words together, left justify cur = " ".join(words[start: start+cnt]) if len(cur) < maxWidth: cur+= " "*(maxWidth-len(cur)) res.append(cur) else: #common line avg = (maxWidth - lengthSum)/(cnt-1) if (maxWidth - lengthSum)%(cnt-1) == 0: res.append((" "*avg).join(words[start:start+cnt])) else: n1 = maxWidth - lengthSum - avg*(cnt-1) + 1#number of left slots has more space n2 = avg - (cnt-1) cur =(" "*(avg+1)).join(words[start:start+n1]) cur += " "*avg cur += (" "*avg).join(words[start+n1:start+cnt]) res.append(cur) start += cnt return res
参考leetcode精简思路,找长度一样,主要是生成行的时候简单:
vector<string> fullJustify(vector<string> &words, int L) { vector<string> res; for(int i = 0, k, l; i < words.size(); i += k) { for(k = l = 0; i + k < words.size() and l + words[i+k].size() <= L - k; k++) { l += words[i+k].size(); } string tmp = words[i]; for(int j = 0; j < k - 1; j++) { if(i + k >= words.size()) tmp += " "; else tmp += string((L - l) / (k - 1) + (j < (L - l) % (k - 1)), ' '); tmp += words[i+j+1]; } tmp += string(L - tmp.size(), ' '); res.push_back(tmp); } return res; }