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




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章