LeetCode 68 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 exactly Lcharacters.

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."]
L: 16.

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.
思路:这道题是道简单题,但也是道难题,难在非常多细节。
细节1.最后一行不须要插入额外的空格。
细节2.空格要均匀--->非最后一行,随意两个相邻的单词之间的空格数相差最多为1,且左边的一定不比右边的少,eg AAA___BBB___CCC___DD__EE__FF。
细节3.每一行是左对齐的,即每个string开头不能有空格。
细节4. 非最后一行,不能以空格结尾。
	public List<String> fullJustify(String[] words, int L) {
		ArrayList<String> result = new ArrayList<String>();
		String str = new String("");
		int i, j;
		for (i = 0; i < L; i++) {
			str += " ";
		}

		StringBuffer sb = new StringBuffer("");
		for (i = 0, j = 1; i < words.length; i++) {
			if (sb.length() == 0) {
				sb.append(words[i]);
				j = 1;
			} else if (sb.length() + 1 + words[i].length() == L) {
				sb.append(" " + words[i]);
				result.add(sb.toString());
				sb = new StringBuffer("");
			} else if (sb.length() + 1 + words[i].length() < L) {
				sb.append(" " + words[i]);
				j++;
			} else if ((sb.length() < L && j > 1)) {
				int n = (L - sb.length()) / (j - 1);
				int m = (L - sb.length()) % (j - 1);
				int len = sb.length();
				for (int k = 1; k < j; k++) {
					len -= (words[i - k].length() + 1);
					if (m + k >= j)
						sb.insert(len, str.substring(0, n + 1));
					else
						sb.insert(len, str.substring(0, n));
				}
				result.add(sb.toString());
				sb = new StringBuffer(words[i]);
				j = 1;
			} else if (sb.length() <= L && j == 1) {
				sb.append(str.substring(0, L - sb.length()));
				result.add(sb.toString());
				sb = new StringBuffer(words[i]);
			}
		}
		if (sb.length() < L) {
			sb.append(str.substring(0, L - sb.length()));
		}
		result.add(sb.toString());
		return result;
	}
}




转载于:https://www.cnblogs.com/blfshiye/p/4558778.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值