leetcode 68. 文本左右对齐

题目:68. 文本左右对齐 - 力扣(LeetCode)

没啥难的,就是麻烦点。

cpp 复制代码
class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        vector<string> ret;
        vector<string> temp;
        int w = 0;
        int total = 0;
        int spaces;
        int a, b;
        string line;
        for (int i = 0; i < words.size(); i++) {
            if (w + words[i].length() > maxWidth) {
                spaces = maxWidth - total;
                line = "";
                if (temp.size() == 1) {
                    line = temp[0];
                    for (int j = 0; j < spaces; j++) {
                        line += " ";
                    }
                } else {
                    a = spaces / (temp.size() - 1);
                    b = spaces % (temp.size() - 1);
                    for (int j = 0; j < temp.size(); j++) {
                        line += temp[j];
                        if (j == temp.size() - 1) {
                            break;
                        }
                        for (int k = 0; k < a; k++) {
                            line += " ";
                        }
                        if (b > 0) {
                            line += " ";
                            --b;
                        }
                    }
                }
                ret.push_back(line);
                temp.clear();
                w = 0;
                total = 0;
            }
            temp.push_back(words[i]);
            w += words[i].length() + 1;
            total += words[i].length();
        }
        line = "";
        for (int i = 0; i < temp.size(); i++) {
            if (i) {
                line += " ";
            }
            line += temp[i];
        }
        while (line.size() < maxWidth) {
            line += " ";
        }
        ret.push_back(line);
        return ret;
    }
};
相关推荐
LYFlied13 分钟前
【每日算法】LeetCode 300. 最长递增子序列
前端·数据结构·算法·leetcode·职场和发展
闲看云起34 分钟前
LeetCode-day2:字母异位词分组分析
算法·leetcode·职场和发展
Swift社区1 小时前
LeetCode 457 - 环形数组是否存在循环
算法·leetcode·职场和发展
youngee113 小时前
hot100-53搜索旋转排序数组
数据结构·算法·leetcode
Tisfy3 小时前
LeetCode 2483.商店的最少代价:两次遍历 -> 一次遍历
算法·leetcode·题解·遍历
YGGP3 小时前
【Golang】LeetCode 279. 完全平方数
算法·leetcode
im_AMBER3 小时前
Leetcode 87 等价多米诺骨牌对的数量
数据结构·笔记·学习·算法·leetcode
月明长歌4 小时前
【码道初阶】Leetcode771 宝石与石头:Set 判成员 vs List 判成员(同题两种写法的差距)
java·数据结构·leetcode·list·哈希算法·散列表
YGGP4 小时前
【Golang】LeetCode198. 打家劫舍
算法·leetcode
YGGP4 小时前
【Golang】LeetCode 152. 乘积最大子数组
算法·leetcode