LeetCode 68 Text Justification

题意:

给出许多单词和一行能显示的最大长度,将所有单词按照两端对齐的方式进行排版,最后一行左对齐并用空格补齐长度。


思路:

一行一行的排版,每一行检查最多能放几个单词,即先假设单词之间只用1个空格分隔。

确定了一行要显示的单词数后,判断是否为最后一行,如果是,那么单词间用1个空格分隔,最后补空格到行最大长度;若不是最后一行,则每个单词后跟几个空格需要计算,计算方法见代码19和20行。


代码:

class Solution {
public:
    vector <string> fullJustify(vector <string> &words, int maxWidth) {
        vector <string> ans;
        for (int i = 0; i < words.size();) {
            int count = words[i].size();
            int num = 1;
            int j = i + 1;
            while (j < words.size()) {
                if (count + words[j].size() + num > maxWidth) {
                    break;
                }
                count += words[j].size();
                ++num;
                ++j;
            }
            stringstream ss;
            if (j != words.size() && num > 1) {
                int space = (maxWidth - count) / (num - 1);
                int last = (maxWidth - count) - (num - 1) * space;
                ss << words[i++];
                while (i < j) {
                    for (int k = 1; k <= space; ++k) {
                        ss << ' ';
                    }
                    if (last) {
                        --last;
                        ss << ' ';
                    }
                    ss << words[i++];
                }
                ans.push_back(ss.str());
            } else {
                ss << words[i++];
                while (i < j) {
                    ss << ' ' << words[i++];
                }
                for (int k = count + num; k <= maxWidth; ++k) {
                    ss << ' ';
                }
                ans.push_back(ss.str());
            }
        }
        return ans;
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值