[LeetCode] 68. Text Justification

思路:
这题用的强行模拟, 自己做出来了还挺高兴的, 会遍历两次words, 所以是O(n)的时间复杂度, 用时0ms.

int generateNextString(vector<string>& words, string& candidate, int start, int maxWidth) {
    // 如果当前是最后一个单词, 直接向左对齐,然后补空格,返回
    if (start == words.size() - 1) {
        candidate = words.back();
        candidate += string(maxWidth - candidate.length(), ' ');
        return words.size() - 1;
    }
    // 计算当前串能容纳到words中的哪个字符串
    int end = -1, count = 0;
    for (int i = start; i < words.size(); i++) {
        if (count + words[i].length() + 1 > maxWidth + 1) {
            end = i - 1;
            break;
        }
        else count += words[i].length() + 1;
    }
    // 如果end没有变化, 就说明从start到words最后都能放到当前串
    if (end == -1) {
        end = words.size() - 1;
        for (int i = start; i <= end; i++) {
            candidate += words[i];
            candidate += ' ';
        }
        candidate += string(maxWidth - candidate.length(), ' ');
        return end;
    }
    // 如果只能放下一个串
    if (end == start) {
        candidate = words[start];
        candidate += string(maxWidth - candidate.length(), ' ');
        return end;
    }
    // 最后的情况, end在start和words最后一个元素的索引之间
    count -= end - start + 1;
    int baseIntervalSpaces = (maxWidth - count) / (end - start);
    int extraIntervalSpaces = (maxWidth - count) % (end - start);
    for (int i = start; i <= end; i++) {
        candidate += words[i];
        if (i == end) break;
        candidate += string(baseIntervalSpaces, ' ');
        if (extraIntervalSpaces-- > 0)
            candidate += ' ';
    }

    return end;
}

vector<string> fullJustify(vector<string>& words, int maxWidth) {
    vector<string> res;
    string candidate = "";
    int i = 0;
    while (i < words.size()) {
        i = generateNextString(words, candidate, i, maxWidth) + 1;
        res.push_back(candidate);
        candidate.clear();
    }
    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值