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.
感觉更加像阅读理解题,关键是两点,1.每一行都要有L个字符,最后一行每个单词只间隔一个空格,剩下的用空格补到L长。2.如果多余的空格不能均匀分布,假设有i个多余空格,就将这i个分别插入到当前行的第1,2,。。i个可以插空格的地方。
AC代码:
class Solution { public: vector<string> fullJustify(vector<string> &words, int L) { vector<string> ret; int minSize = -1; vector<string> line; for(int i = 0; i < words.size(); ++i){ if(minSize + words[i].size() + 1 <= L){ //攒一行单词存到line里 minSize += words[i].size() + 1; line.push_back(words[i]); }else{ --i; int space = 0; int left = 0; string tempLine; if (line.size() == 1) { //如果某行只有一个单词 tempLine += line[0] + string(L- minSize, ' '); }else{ //否则计算空格数 space = (L - minSize) / (line.size() - 1); left = (L- minSize) % (line.size() - 1); for(int j = 0; j < line.size(); ++j){ if(j == line.size() - 1) tempLine += line[j]; else{ if(left-- > 0) tempLine += line[j] + string(space + 1, ' ') + " "; else tempLine += line[j] + string(space + 1, ' '); } } } ret.push_back(tempLine); line.clear(); minSize = -1; } } if(line.size()){ //处理最后一行 string tempLine; for(int j = 0; j < line.size(); ++j){ if(j != line.size() - 1) tempLine += line[j] + " "; else tempLine += line[j]; } int space = L - (int)tempLine.size(); tempLine += string(space, ' '); ret.push_back(tempLine); } return ret; } };
浙公网安备 33010602011771号