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 Lcharacters.
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 { public: vector<string> fullJustify(vector<string> &words, int L){ vector<string> result; // input validation if(words.empty()) return result; // param @ i 遍历单词的下标临时变量 // param @ k 校正后每行单词个数 // param @ l 每行字符(除空格)个数 // 每次遍历构造一行 将单词检索进新数组 for(int i = 0, k, l; i < words.size(); i += k){ // 查询单词不能越界 并且每行增添的单词需要满足要满足中间能插入空格 // for(k = 0, l = 0; k+i < words.size() && l + words[i+k].size()<= L-k; l += words[i+k].size(), ++k); // 构造新行 string temp = words[i]; // 每行首单词 for(int j = 0; j < k-1; ++j){ int blanks = (L-l)/(k-1) + (j < (L-l)%(k-1)); // 已经是最后一行单词,要求左对齐,每个单词之间一个空格,剩下空格放在最后 if(i+k >= words.size()){ temp += " "; } else temp += string(blanks, ' '); temp += words[i+j+1]; } // 补全空格 temp += string(L-temp.size(), ' '); result.push_back(temp); } return result; } };