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;
    }
};
相关推荐
夏鹏今天学习了吗7 小时前
【LeetCode热题100(56/100)】组合总和
算法·leetcode·职场和发展
微笑尅乐8 小时前
三种方法解开——力扣3370.仅含置位位的最小整数
python·算法·leetcode
夏鹏今天学习了吗15 小时前
【LeetCode热题100(57/100)】括号生成
算法·leetcode·职场和发展
三花聚顶<>15 小时前
310.力扣LeetCode_ 最小高度树_直径法_DFS
算法·leetcode·深度优先
努力学算法的蒟蒻16 小时前
day04(11.2)——leetcode面试经典150
算法·leetcode
Tisfy18 小时前
LeetCode 3217.从链表中移除在数组中存在的节点:哈希表(一次遍历)
leetcode·链表·散列表
小白菜又菜18 小时前
Leetcode 495. Teemo Attacking
算法·leetcode·职场和发展
.柒宇.1 天前
力扣hot100----15.三数之和(java版)
java·数据结构·算法·leetcode
程序员阿鹏1 天前
56.合并区间
java·数据结构·算法·leetcode
Brookty1 天前
【算法】位运算| & ^ ~ -n n-1
学习·算法·leetcode·位运算