leetcode做题记录0068

leetcode 0068

说明

只是为了记录一下,不求多快,也不深究。

会简要描述思路,代码中不写注释。

如碰到不会做的用了别人代码会在博客中标出。

题目描述

在这里插入图片描述

思路

这题有点烦人,花了好长时间。

就一个个往里加,单词个数确定后在添加空格,加到长度为maxWidth为止。

不想多说了,这题烦的一批。

class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {
		StringBuilder sb = new StringBuilder();
		List<String> ls = new ArrayList<String>();
		int i = 0;
		int count = 0;
		while (true) {
			if (sb.length() == 0) {
				sb.append(words[i]);
				count++;
				i++;
				continue;
			}
			if (i < words.length && sb.length() + words[i].length() + 1 <= maxWidth) {
				sb.append(" " + words[i]);
				count++;
				i++;
				continue;
			} else {
				if (count == 1 || i == words.length) {
					while (sb.length() < maxWidth) {
						sb.append(' ');
					}
					ls.add(sb.toString());
					sb.delete(0, sb.length());
					count = 0;
					if (i == words.length) {
						break;
					}
					continue;
				} else {
					int countSpace = maxWidth - sb.length();
					int a = countSpace / (count - 1);
					String spaces = " ";
					while (spaces.length() <= a) {
						spaces = spaces + " ";
					}
					String s = sb.toString();
					s = s.replace(" ", spaces + " ");
					while (s.length() > maxWidth) {
						int place = s.lastIndexOf(spaces + " ");
						StringBuilder sb2 = new StringBuilder(s);
						sb2 = sb2.replace(place, place + 1, "");
						s = sb2.toString();
					}
					ls.add(s);
					sb.delete(0, sb.length());
					count = 0;
					continue;
				}
			}
		}
		return ls;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值