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;
    }
};
相关推荐
老鼠只爱大米6 小时前
LeetCode经典算法面试题 #295:数据流的中位数(双堆法、有序列表、平衡树等多种实现方案详解)
算法·leetcode·优先队列··数据流·中位数·java 面试题
x_xbx6 小时前
LeetCode:215. 数组中的第K个最大元素
数据结构·算法·leetcode
进击的荆棘7 小时前
优选算法——分治
数据结构·算法·leetcode·分治
木井巳8 小时前
【递归算法】找出所有子集的异或总和再求和
java·算法·leetcode·决策树·深度优先
Aaswk9 小时前
回溯算法的本质理解
c语言·算法·leetcode·力扣·剪枝
迷海9 小时前
力扣原题《分发糖果》,采用二分原则,纯手搓,待验证
c++·算法·leetcode
玛卡巴卡ldf9 小时前
【LeetCode 手撕算法】(普通数组)53-最大子数组和、56-合并区间、189-轮转数组、238-除了自身以外数组的乘积
数据结构·算法·leetcode
Sakinol#9 小时前
Leetcode Hot 100 ——动态规划part02
算法·leetcode·动态规划
Frostnova丶10 小时前
LeetCode 238 & 2906.构造乘积数组与乘积矩阵
算法·leetcode·矩阵
im_AMBER11 小时前
Leetcode 145 回文数 | 加一
数据结构·算法·leetcode