您的位置:首页 > 其它

LeetCode 068 Text Justification

2015-10-05 16:57 309 查看

题目描述

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.

代码

[code]

    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;

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: