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;
    }
};
相关推荐
仰泳的熊猫3 小时前
LeetCode:95. 不同的二叉搜索树 II
数据结构·c++·算法·leetcode
前进之路94 小时前
Leetcode每日一练--28
leetcode
海琴烟Sunshine6 小时前
leetcode 168. Excel 表列名称 python
python·算法·leetcode
1白天的黑夜16 小时前
递归-21.合并两个有序链表-力扣(LeetCode)
c++·leetcode·链表·递归
坚持编程的菜鸟7 小时前
LeetCode每日一题——在区间范围内统计奇数数目
c语言·算法·leetcode
前进之路97 小时前
Leetcode每日一练--35
算法·leetcode
微笑尅乐8 小时前
三种思路彻底掌握 BST 判断(递归与迭代全解析)——力扣98.验证二叉搜索树
算法·leetcode·职场和发展
白云千载尽10 小时前
leetcode 2598 执行操作后最大MEX
算法·leetcode·职场和发展
Seven9712 小时前
剑指offer-35、数组中的逆序对
java·leetcode