LeetCode68——Text Justification

LeetCode68——Text Justification

也是相当恶心的一道题,倒不是有多难,还是不知道他的边界条件是怎么样的,所以也是经过多次的提交取改进代码,最后通过。

就不细说了,代码:

class Solution {
private:
	void removeBackSpace(string &s)
	{
		int i = s.size() - 1;
		while (i >= 0 && s[i] == ' ')
		{
			s.pop_back();
			i--;
		}
	}
public:
	vector<string> fullJustify(vector<string>& words, int maxWidth) {
		int i = 0;
		int lenSum = 0;
		int count = 0;
		int space;
		vector<string> result;
		while (i < words.size())
		{
			int j = i;
			lenSum = 0;
			int tempSum = lenSum + j - i;
			while (j<words.size()&&tempSum <= maxWidth)
			{
				lenSum += words[j].size();
				j++;
				tempSum = lenSum + j - i;
			}
			if (tempSum - 1 > maxWidth)
			{
				j--;
				lenSum -= (words[j].size());
			}
			int distance = j - i;
			if (distance > 1)
			{
				if (j != words.size())
				{
					space = (maxWidth - lenSum) / (distance - 1);
					vector<char> tempspace(space, ' ');
					string spaceWord(tempspace.begin(), tempspace.end());
					string temp;
					for (int k = i; k < j; k++)
					{
						temp += words[k];
						temp += spaceWord;
					}
					removeBackSpace(temp);
					if (temp.size() < maxWidth)
					{
						int count = maxWidth - temp.size();
						for (int k = 0; count > 0 && k < temp.size(); k++)
						{
							if (temp[k] == ' ')
							{
								temp.insert(temp.begin() + k, ' ');
								k++;
								count--;
								continue;
							}
						}
					}
					result.push_back(temp);
				}
				else
				{
					space = 1;
					vector<char> tempspace(space, ' ');
					string spaceWord(tempspace.begin(), tempspace.end());
					string temp;
					for (int k = i; k < j; k++)
					{
						temp += words[k];
						temp += spaceWord;
					}
					removeBackSpace(temp);
					if (temp.size() < maxWidth)
					{
						int count = maxWidth - temp.size();
						while (count > 0)
						{
							temp.insert(temp.end(), ' ');
							count--;
						}
					}
					result.push_back(temp);
				}
			}
			else if (distance == 1)
			{
				string temp = words[j - 1];
				vector<char>tempspace(maxWidth-words[j-1].size(), ' ');
				string spaceWord(tempspace.begin(),tempspace.end());
				temp += spaceWord;
				result.push_back(temp);
			}
			else
			{
				string temp = words[j];
				vector<char>tempspace(maxWidth - words[j].size(), ' ');
				string spaceWord(tempspace.begin(), tempspace.end());
				temp += spaceWord;
				result.push_back(temp);
				j++;
			}
			i = j;
		}
		return result;
	}
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值