凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 68. Text Justification

分类:algorithm| 发布时间:2017-04-05 11:12:00


题目

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.

题意

给出一组单词以及长度 L。格式化文本使得每一行的长度刚好是 L。

解法

class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        vector<string> ret;
        int currentLen = 0, begin = 0, i = 0;
        for (; i < words.size(); ++i) {
            if (currentLen + words[i].size() + (i - begin) > maxWidth) {
                packToLine(words, begin, i, currentLen, maxWidth, ret);
                begin = i;
                currentLen = words[i].size();
            } else {
                currentLen += words[i].size();
            }
        }

        lastPack(words, begin, words.size(), currentLen, maxWidth, ret);
        return ret;
    }

    void packToLine(vector<string> &words, int begin, int end, int currentLen, int maxWidth, vector<string> &ret) {
        const int space = maxWidth - currentLen;
        if (end == begin + 1) {
            string s = words[begin];
            s.append(space, ' ');
            ret.push_back(s);
            return;
        }

        int pad = space ? space / (end - begin - 1) : 0;
        int extra = space ? space % (end - begin - 1) : 0;
        string s;
        for (int i = begin; i < end - 1; ++i) {
            s += words[i];
            s.append(pad, ' ');
            if (extra) {
                s.push_back(' ');
                --extra;
            }
        }

        s += words[end - 1];
        ret.push_back(s);
    }

    void lastPack(vector<string> &words, int begin, int end, int currentLen, int maxWidth, vector<string> &ret) {
        int space = maxWidth - currentLen;
        string s;
        for (int i = begin; i < end; ++i) {
            s += words[i];
            if (space) {
                s.push_back(' ');
                --space;
            }
        }

        if (space)
            s.append(space, ' ');

        ret.push_back(s);
    }
};