国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

68. Text Justification

2019-11-14 10:22:07
字體:
供稿:網(wǎng)友

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.

給出一個(gè)字符串?dāng)?shù)組,要求變換成另一個(gè)字符串?dāng)?shù)組,要求是組成的每個(gè)字符串的長度為maxWidth(用貪心算法),原字符間要用空格隔開,不夠長的話在字符間填充空格,規(guī)則是間隔要盡量均勻,如果間隔的空格數(shù)不能完全相等,靠左邊的要分多點(diǎn)。最后一行和前面的規(guī)則不一樣,最后一行間隔為1個(gè)空格,剩余的空格都填充在后面。實(shí)現(xiàn)時(shí)就是遍歷累加字符長度,適當(dāng)長時(shí)就按上面的規(guī)則,計(jì)算出各間隔空格數(shù),組合成字符串,加到答案中,同時(shí)也令累加長度為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;	}};


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 义马市| 安顺市| 巴里| 建水县| 雅安市| 高雄县| 廉江市| 绥德县| 甘孜| 合川市| 吴旗县| 古田县| 阳曲县| 自治县| 宜君县| 定陶县| 武邑县| 正宁县| 饶平县| 育儿| 桦川县| 张家界市| 大宁县| 丘北县| 长春市| 德保县| 自贡市| 闵行区| 河南省| 巴林左旗| 多伦县| 岑巩县| 泸溪县| 花莲县| 石首市| 昌吉市| 连山| 青河县| 瑞丽市| 册亨县| 昌吉市|