leetcode 68: Text Justification

本文介绍了一种用于将文本按指定宽度完全对齐的算法实现。该算法能够处理多种情况,包括仅能容纳一个单词的特殊情况、最后一行的处理方式以及常规情况下多个单词之间的间距分配。通过使用C++编程语言并借助标准模板库,本文详细展示了如何在不同条件下对文本进行合理的对齐。

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

class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        int i,j;
        int width=0;
        vector<string> res;
        if(words[0].empty())
        {
            string s="";
            for(int x=0;x<maxWidth;x++)
                s+=' ';
            res.push_back(s);
            return res;
        }
        for(i=0,j=i;j<=words.size();j++)
        {
            if(j==words.size()||width+words[j].size()+j-i>maxWidth)
            {
                int num_space=maxWidth-width;//number of space to be added
                int num_slot=j-i-1;//number of slots between a line of words
                string s;
                if(j-i==1)//a line can only fit one word
                {
                    s+=words[i];
                    for(int x=0;x<num_space;x++)
                        s+=' ';
                }
                else if(j==words.size())//reaches the last word
                {
                    for(int x=i;x<j;x++)
                        s+=words[x]+' ';
                    for(int x=0;x<num_space-(j-i);x++)
                        s+=' ';
                }
                else//length of words can fit maxWidth
                {
                    string slot;
                    for(int x=0;x<num_space/num_slot;x++)
                        slot+=' ';
                    s+=words[i];
                    int rem=num_space%num_slot;
                    for(int x=i+1;x<j;x++)
                    {
                        s+=slot;
                        if(rem)
                        {
                            s+=' ';
                            rem--;
                        }
                        s+=words[x];
                    }
                }
                res.push_back(s);
                width=0;
                i=j;
            }
            if(j<words.size())
                width+=words[j].size();
        }
        return res;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值