Text Justification greedy

本文介绍了一种使用贪心算法解决文本换行问题的方法,通过优化空格分配,实现文本在指定宽度下的美观排列。算法的时间复杂度为O(N),空间复杂度为O(1),适用于各种文本编辑和排版场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:

贪心。时间复杂度O(N),空间复杂度O(1)。

class Solution {
private:
/**
    add space to a target line
    @param s : target line
    @param i : current space's number
    @param n : interspace sum
    @param L : space sum
    @param is_last : whether is the last line
    @return
*/
void addSpaces(string &s, int i, int n, int L, bool is_last) {
    if(n < 1 || i > n - 1) return;

    int spaces = is_last ? 1 : (L/n + (i < (L%n) ? 1 : 0));
    s.append(spaces, ' ');
}
/**
    connect words[begin, end] to a line
    @param words
    @param begin
    @param end
    @param len : the length of words[begin, end]
    @param maxWidth
    @param is_last : whether if is the last line
    @return the connected line
*/
string connect(vector<string> &words, int begin, int end, int len, int maxWidth, bool is_last) {
    string s;
    int n = end - begin + 1;// words number

    for(int i = 0; i < n; ++i) {
        s += words[begin + i];
        addSpaces(s, i, n - 1, maxWidth - len, is_last);
    }

    if(s.size() < maxWidth) {
        s.append(maxWidth - s.size(), ' ');
    }
    return s;
}
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        vector<string> res;
        const int n = words.size();

        int begin = 0, len = 0;//current line's starting point, current line's length
        for(int i = 0; i < n; ++i) {
            if(len + words[i].size() + (i - begin) > maxWidth) {
                res.push_back(connect(words, begin, i-1, len, maxWidth, false));
                begin = i;
                len = 0;
            }
            len += words[i].size();
        }
        res.push_back(connect(words, begin, n-1, len, maxWidth, true));
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值