Text Justification 题解


题目描述

Text Justification
即文本对齐:填充单词之间空格使得占满一行(除了最后一行左对齐)。
如:words: ["This", "is", "an", "example", "of", "text", "justification."],L: 16.
对齐后:

"This    is    an"
"example  of text"
"justification.  "

题解

预读单词,得到每一行的单词最大容纳量,计算单词间的空格数。设总字符串长度为N,时间复杂度为O(N),空间复杂度为O(N)

代码

class Solution {
public:
    vector<string> fullJustify(vector<string>& words, size_t maxWidth) {
        if (words.size() == 0U)
            return std::vector<std::string>();
        std::vector<std::string> justify; justify.reserve(words.size());
        for (size_t len = words.size(), i = 0U; 1;) {
            std::string lineStr(words[i]); lineStr.reserve(maxWidth);
            size_t left = words[i].size(), start = i;
            while (++i < len) {
                size_t next = words[i].size() + 1U;
                if (left + next > maxWidth)
                    goto Justify;
                left += next;
            }
            for (; ++start < i; lineStr.append(words[start]))
                lineStr += ' ';
            lineStr.resize(maxWidth, ' ');
            justify.push_back(std::move(lineStr));
            break;
        Justify:
            size_t gap = i - start - 1U;
            if (gap) {
                size_t extra = maxWidth - left, add = extra / gap + 2U, mod = start + extra % gap;
                for (; ++start <= mod; lineStr.append(words[start]))
                    lineStr.append(add, ' ');
                for (--add; start < i; lineStr.append(words[start++]))
                    lineStr.append(add, ' ');
            } else {
                lineStr.resize(maxWidth, ' ');
            }
            justify.push_back(std::move(lineStr));
        }
        return std::move(justify);
    }
};

总结

主要应用了预读的思想。


Caesar
53 声望1 粉丝

Hustle-As-A-Service


« 上一篇
Valid Number
下一篇 »
Edit Distance