Leetcode 068 Text Justification(模拟)

题目连接:Leetcode 068 Text Justification

解题思路:纯模拟,每次挑选单词,直到长度超过最大宽度,注意单词与单词之间最少空一格,也就是有n个单词的时候,要有n-1个空格。确定一行的单词后,根据单词数,确定间隔,不能整除是,平摊余数。

class Solution {
	public:
		string full(vector<string>& words, int start, int end, int maxWidth) {
			string ans = "";
			int n = end - start, c = 0;
			for (int i = start; i <= end; i++) c += words[i].size();
			int space = maxWidth - c;
			int gap = n ? space / n: 0, res = n ? space % n : space;
			if (end + 1 == words.size()) gap = 1, res = 0;

			for (int i = start; i <= end; i++) {
				ans += words[i];
				if (i < end) {
					for (int j = 0; j < gap; j++) ans += " ";
					if (i - start < res) ans += " ";
				}
			}
			while (ans.size() < maxWidth) ans += " ";

			return ans;
		}

		vector<string> fullJustify(vector<string>& words, int maxWidth) {
			vector<string> ans;
			int n = words.size(), p = 0;
			while (p <  n) {
				int t = p + 1, c = words[p].size();
				while (t < n && c + words[t].size() + 1 <= maxWidth) { c += words[t++].size() + 1; }
				string tmp = full(words, p, t - 1, maxWidth);
				ans.push_back(tmp);
				p = t;
			}
			return ans;
		}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值