首页 > 学院 > 开发设计 > 正文

68. Text Justification

2019-11-14 10:22:07
字体:
来源:转载
供稿:网友

Given an array of Words and a length L, format the text such that each line has exactlyL 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.

给出一个字符串数组,要求变换成另一个字符串数组,要求是组成的每个字符串的长度为maxWidth(用贪心算法),原字符间要用空格隔开,不够长的话在字符间填充空格,规则是间隔要尽量均匀,如果间隔的空格数不能完全相等,靠左边的要分多点。最后一行和前面的规则不一样,最后一行间隔为1个空格,剩余的空格都填充在后面。实现时就是遍历累加字符长度,适当长时就按上面的规则,计算出各间隔空格数,组合成字符串,加到答案中,同时也令累加长度为0重新累加。

代码:

class Solution{public:	vector<string> fullJustify(vector<string>& words, int maxWidth) 	{		vector<string> res;		if(words.empty()) return res;		int n = words.size(), p = 0, len = 0, i = 0;		words.push_back(" ");		for(i; i <= n; ++i)		{			if(len + words[i].size() + i - p > maxWidth || i == n)			{				int r = maxWidth - len, space, addition, d = 1;				if(i == n)				{					space = 1;					addition = 0;				}				else if(i - p - 1 <= 0) 				{					space = r;					addition = 0;				}				else				{					space = r / (i - p - 1);					addition = r % (i - p - 1);				}				string tmp;				for(p; p < i; ++p)				{					tmp += words[p];					if(p == i - 1) continue;					if(addition-- <= 0) d = 0;					tmp += string(space + d, ' ');				}				while(tmp.size() < maxWidth) tmp += " ";				res.push_back(tmp);				len = 0;			}			len += words[i].size();		}		return res;	}};


上一篇:0010 继承

下一篇:时间复杂度公式

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表