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;
    }
};
相关推荐
不想编程小谭2 小时前
力扣LeetCode: 2506 统计相似字符串对的数目
c++·算法·leetcode
01_3 小时前
力扣hot100——LRU缓存(面试高频考题)
leetcode·缓存·面试·lru
_Itachi__4 小时前
LeetCode 热题 100 73. 矩阵置零
算法·leetcode·矩阵
夏末秋也凉5 小时前
力扣-贪心-376 摆动序列
算法·leetcode
01_5 小时前
力扣hot100 ——搜索二维矩阵 || m+n复杂度优化解法
算法·leetcode·矩阵
SylviaW085 小时前
python-leetcode 35.二叉树的中序遍历
算法·leetcode·职场和发展
篮l球场5 小时前
LeetCodehot 力扣热题100
算法·leetcode·职场和发展
qy发大财6 小时前
分发糖果(力扣135)
数据结构·算法·leetcode
小王努力学编程9 小时前
【算法与数据结构】单调队列
数据结构·c++·学习·算法·leetcode
夏末秋也凉11 小时前
力扣-贪心-53 最大子数组和
数据结构·算法·leetcode