LeetCode 068 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 L characters.

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.

代码



 String space(int len) { char[] s = new char[len]; Arrays.fill(s, ' '); return new String(s); } public List<String> fullJustify(String[] words, int L) { ArrayList<String> text = new ArrayList<String>(); int p = 0; int lastp = 0; while (p < words.length) { if (L == 0 && "".equals(words[p])) { text.add(""); p++; continue; } int l = 0; while (l < L && p < words.length) { l += words[p++].length() + 1; } if (l - 1 > L) l -= words[--p].length() + 1; int count = p - lastp; int left = L - l + count; int add; if (count == 1) add = left; else if (p - 1 == words.length - 1) { add = 1; left = count - 1; } // fuck... else add = left / (count - 1); left -= add * (count - 1); String s = ""; for (int i = lastp; i < p - 1; i++) { if (left > 0) { s += words[i] + space(add + 1); left--; } else { s += words[i] + space(add); } } left = L - s.length() - words[p - 1].length(); if (count == 1 || p - 1 == words.length - 1) // fuck... s += words[p - 1] + space(left); else s += space(left) + words[p - 1]; text.add(s); lastp = p; } return text; } 
    原文作者:_我们的存在
    原文地址: https://blog.csdn.net/Yano_nankai/article/details/48915241
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞