Text Justification

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

总结

主要应用了预读的思想。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值