LeetCode-Text Justification-文字调整-情况比较复杂

https://oj.leetcode.com/problems/text-justification/

这个题目没有什么算法。但是要实现还是比较麻烦,一次写对基本不可能。注意理解清楚题意,写完程序脑子里过一遍再编译可能会好一点。

主要就是每次扫面一行以内的,正确的数算上最小空格数量能放下的单词,并统计每个后面需要加的空格个数。

class Solution {
public:
	int n,m;
	vector<string> fullJustify(vector<string> &words, int L) {
		n=words.size();
		int s=0;
		vector <string> res;
		while(s<n){
			int count=0;
			int end=n;
			int chCount=0;
			bool contFlag=false;
			for (int i=s;i<n;i++){
			    if (i==s){
			        if (count+words[i].length()>L){
			            end=i;
			            break;
			        }
			    }
			    else{
			        if (count+words[i].length()+1>L){
			            end=i;
			            break;
			        }
			    }
				chCount+=words[i].length();
				count+=words[i].length();
				if (i>s){count+=1;}
			}
			int spaceNum=L-chCount;
			int betNum=end-s-1;
			if (betNum==0){betNum=1;}
			int unitNum=spaceNum / betNum;
			int redNum=spaceNum % betNum;
			string cur;
			if (end==n){
			    for (int i=s;i<end;i++){
			        if (i>s){
			            cur+=" ";
			        }
			        cur+=words[i];
			    }
			    if (L>cur.length()){
			        cur+=string(L-cur.length(),' ');
			    }
			    res.push_back(cur);
			    s=end;
			    continue;
			}
			for (int i=s;i<end;i++){
				cur+=words[i];
				if (i+1==end && end-s>1){continue;}
				cur+=string(unitNum,' ');
				if (redNum){
					cur+=" ";
					redNum--;
				}
			}
			res.push_back(cur);
			s=end;
		}
		return res;
	}
};

  

转载于:https://www.cnblogs.com/yangsc/p/4004619.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值