首页 > 代码库 > LeetCode 68 Text Justification

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

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;
	}
}




LeetCode 68 Text Justification