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;
    }
};
相关推荐
是代码侠呀1 小时前
从前端视角看网络协议的演进
leetcode·开源·github·github star·github 加星
刃神太酷啦3 小时前
类和对象(1)--《Hello C++ Wrold!》(3)--(C/C++)
java·c语言·c++·git·算法·leetcode·github
I AM_SUN4 小时前
994. 腐烂的橘子
数据结构·c++·算法·leetcode·职场和发展
Tisfy5 小时前
LeetCode 3341.到达最后一个房间的最少时间 I:Dijkstra算法(类似深搜)-简短清晰的话描述
leetcode··最短路·dijkstra·题解·迪杰斯特拉
_Itachi__18 小时前
LeetCode 热题 100 543. 二叉树的直径
java·算法·leetcode
Tisfy21 小时前
LeetCode 1550.存在连续三个奇数的数组:遍历
算法·leetcode·题解·数组·遍历
wang__1230021 小时前
力扣70题解
算法·leetcode·职场和发展
_Itachi__1 天前
LeetCode 热题 100 101. 对称二叉树
算法·leetcode·职场和发展
阳洞洞1 天前
leetcode 15. 三数之和
leetcode·双指针
Mi Manchi261 天前
力扣热题100之合并两个有序链表
算法·leetcode·链表