LeetCode Text Justification

本文介绍了一种使用贪心算法实现文本格式化的解决方案,确保每行文字恰好达到指定长度,并实现左右对齐效果。文章详细解释了如何在单词间均匀分布空格,以及在最后一行采用左对齐方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem:

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

Return the formatted lines as:

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

解题思路:

根据题意,本题所考察的主要算法是贪心算法,通过贪心算法,每一步都要做到最优解,即每一行尽可能多的放置单词。

在编码过程中,由于对"as evenly as possible"这句的语义存在误解,以为是两个单词之间的空格尽可能的是偶数,导致提交多次,最终通过出错的用例才得知题目的要求是两个单词之间的空格数尽可能的均匀。

通过本次编程过程,得到了深刻的教训,碰到不确定的东西不要过早的下定论,必须要去寻找资料进行确认,工作中更是如此,不应出现如此低端的错误,需要谨记!!

本题具体的代码如下:

class Solution {
public:
	vector<string> fullJustify(vector<string>& words, int maxWidth) {
		vector<string> formatted;
		int cur_width = 0;
		vector<string> cur_words;
		for (int i = 0; i < words.size(); )
		{
       			assert(words[i].size() <= maxWidth);
     			if (cur_width + words[i].size() > maxWidth || i == words.size() - 1)
			{
 				if ((cur_width + words[i].size() <= maxWidth) && (i == words.size() - 1))//最后一行的特殊处理
				{				
					cur_words.push_back(words[i]);
					cur_width += words[i].size(); 
					//i++;
					string tmp_format = "";
					int left = maxWidth;
					for (int m = 0; m < cur_words.size(); m++)
					{
						tmp_format += cur_words[m];
						left -= cur_words[m].size();
						if (m == cur_words.size() - 1 && left > 0)
						{
							tmp_format += string(left, ' ');
						}
						else if(left > 0)//添加left > 0防止在一行的最末尾多添加一个空格
						{
							tmp_format += ' ';
							left -= 1;
						}
							
					}
					formatted.push_back(tmp_format);
					break;
				}
				int slots = maxWidth;
				for (int j = 0; j < cur_words.size(); j++)
				{
					slots -= cur_words[j].size();
				}

				//只有1个word并且这个word的长度不小于maxWidth,直接将这个word作为一行存入到formmatted中
				if (slots <= 0 && cur_words.size() == 1)
				{
					formatted.push_back(cur_words[0]);
					cur_width = 0;
					cur_words.clear();
					continue;//当次处理完成
				}

				//两个word之间的slot个数分配策略
				//1.如果这一行只有一个word
				if (cur_words.size() == 1)
				{
					string str_slot(slots, ' ');
					formatted.push_back(cur_words[0] + str_slot);
					cur_width = 0;
					cur_words.clear();
					continue;//当次处理完成
				}

				//2.如果这一行的word数大于1个
				//当前问题是如何使得各word之间的slots尽可能的为偶数,如果整除后不是偶数,则应左边的slots比右边的slots多
				int *arr_slots = new int[cur_words.size() - 1];
				string str_formatted = "";
				get_slots_num(slots, cur_words, arr_slots);
				for (int k = 0; k < cur_words.size(); k++)
				{
					str_formatted += cur_words[k];
					if (k != cur_words.size() - 1)
					{
						str_formatted += string(arr_slots[k], ' ');
					}
				}
				formatted.push_back(str_formatted);
				delete[] arr_slots;
				arr_slots = NULL;
				cur_width = 0;
				cur_words.clear();//当次处理完成
			}
			else
			{
				cur_words.push_back(words[i]);
				cur_width += 1;
				cur_width += words[i].size();
				i++;
			}
		}
		return formatted;
	}

private:
	//给每个slot赋值
	void get_slots_num(int slots, std::vector<std::string> &cur_words, int * arr_slots)
	{
		if (cur_words.size() == 2)
		{
			arr_slots[0] = slots;
			return;
		}
		int avg_slot = slots / (cur_words.size() - 1);
		int left_slot = slots % (cur_words.size() - 1);

		for (int i = 0; i < cur_words.size() - 1; i++) arr_slots[i] = avg_slot;
		int remain = left_slot;
		int x = 0;
		while (remain != 0 && x != cur_words.size())
		{
			arr_slots[x]++;
			remain--;
			x++;
		}
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值