【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."]
L16.

Return the formatted lines as:

[
   "This    is    an",
   "example  of text",
   "justification.  "
]

Note: Each word is guaranteed not to exceed L in length.

Corner Cases:

  • 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.
我的方法是用prev记录下前一行结束的index位置,用一个变量记录下从prev到curr的字符串长度+curr-prev-1(每两个字符串之间有一个空格),如果小于L则将当前字符串接上,else则补上剩余空格输出,然后重置prev。

若用len表示当前字符串长度,则我们得到两个数值blank=(L-len)/count,spe=(L-len)%count,其中count为应插入空格的位置数目。从prev开始计数,当前坐标在spe左边时,插入空格数为blank+1,否则为blank。

代码如下:

class Solution {
public:
	vector<string> fullJustify(vector<string> &words, int L) {
		int whole(0), prev(0);
		vector<string> ret;
		for (int i = 0; i < words.size(); i++){
			int curr = words[i].length();
			if (whole + curr + i - prev>L){
				ret.push_back(generate(prev, i - 1, whole, words, L));
				whole = 0;
			}
			if (!whole)
				prev = i;
			whole += words[i].length();
			if (i == words.size() - 1)
				ret.push_back(generate(prev, i, 0, words, L));
		}
		return ret;
	}
	string generate(int prev, int curr, int whole, vector<string> &words, int L){
		string line;
		if (!whole || prev == curr){
			for (int i = 0; i <= curr - prev; i++){
				line += words[prev + i];
				if (i == curr - prev)
					continue;
				line += " ";
			}
			while (line.length() < L)
				line += " ";
		}
		else{
			int blank = (L - whole) / (curr - prev);
			int spe = (L - whole) % (curr - prev);
			for (int j = 0; j <= curr - prev; j++){
				line += words[prev + j];
				if (j == curr - prev)
					continue;
				int n = blank;
				if (j < spe)
					n += 1;
				for (int k = 0; k < n; k++)
					line += " ";
			}
		}
		return line;
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值