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;
    }
};
相关推荐
代码什么用35 分钟前
LeetCode-42. 接雨水
算法·leetcode
yi0112 小时前
DAY17: LeetCode 139|单词拆分:从“把单词删掉”到用 DP 记录合法切口
人工智能·笔记·python·算法·leetcode·动态规划
Navigator_Z5 小时前
LeetCode //C - 1269. Number of Ways to Stay in the Same Place After Some Steps
c语言·算法·leetcode
垆边人似月.6 小时前
华为算法题:最长连续递增子序列的变
数据结构·算法·leetcode
longlongzihan6 小时前
LeetCode 56合并区间:排序与贪心
c++·算法·leetcode
kukubuzai7 小时前
二分查找系列一
数据结构·算法·leetcode
Cccp.12320 小时前
【leetcode】(七)前缀树和贪心算法
数据结构·leetcode·贪心算法
优质酸酸乳1 天前
力扣100题之21合并两个有序链表
算法·leetcode·链表
旖旎夜光1 天前
LeetCode 137 : 只出现一次的数字 II(位运算) —— 题解
c++·笔记·学习·算法·leetcode·力控