首页 > 代码库 > leetcode | Text Justification
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 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.
这道题正确地处理各种计数,再分情况处理就可以了。
主要分三种情况:
1. 只有一个单词。左对齐,右补空白;
2. 最后一行,单词之间只有一个空白;
3. 其他行,多个单词,那么就要平均空白;如果不能平均,那么就取余数,前几个就要多一个空白,尽量平均;(Line 31-35)
在计算是否能够容纳单词的时候,要算上空白。所以用了一个length计算每个单词之间至少一个空白的总长度,再用sum计算只有单词的总长度,方便计算空格数。(Line 17-18)
1 class Solution { 2 public: 3 vector<string> fullJustify(vector<string> &words, int L) { 4 vector<string> ret; 5 int n = words.size(); 6 if (n == 0) return ret; 7 if (L <= 0) { 8 ret.push_back(""); 9 return ret; 10 } 11 12 int s = 0, e = s, count, pad, sum, length, left; 13 while (true) { 14 if (s >= n) break; 15 sum = length = words[s].length(); 16 for (e = s + 1; e < n && (length + words[e].length() + 1) <= L; ++e) { 17 sum += words[e].length(); 18 length += 1 + words[e].length(); 19 } 20 count = e - s; 21 string tmp(words[s]); 22 if (count == 1) { 23 tmp.append(L - sum, ‘ ‘); 24 } else if (e == n) { 25 for (int i = s + 1; i < e; ++i) { 26 tmp += " " + words[i]; 27 } 28 tmp.append(L - sum - count + 1, ‘ ‘); 29 } else { 30 pad = L - sum; 31 left = pad % (count - 1); 32 pad = pad / (count - 1); 33 for (int i = s + 1; i < e; ++i) { 34 tmp.append(pad, ‘ ‘); 35 if (left-- > 0) tmp.append(1, ‘ ‘); 36 tmp += words[i]; 37 } 38 } 39 ret.push_back(tmp); 40 s = e; 41 } 42 43 return ret; 44 } 45 };