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;
    }
};
相关推荐
1白天的黑夜11 小时前
链表-25.k个一组翻转链表-力扣(LeetCode)
数据结构·leetcode·链表
轴测君4 小时前
3 无重复字符的最长子串
数据结构·算法·leetcode
Greedy Alg9 小时前
LeetCode 438. 找到字符串中所有的字母异位词
算法·leetcode·职场和发展
Q741_1479 小时前
C++ 力扣 76.最小覆盖子串 题解 优选算法 滑动窗口 每日一题
c++·算法·leetcode·双指针·滑动窗口
啊嘞嘞?20 小时前
力扣(滑动窗口最大值)
算法·leetcode·职场和发展
墨染点香20 小时前
LeetCode 刷题【53. 最大子数组和】
数据结构·算法·leetcode
七十二小時1 天前
力扣热题——前K个高频元素
数据结构·算法·leetcode
愚润求学1 天前
【贪心算法】day3
c++·算法·leetcode·贪心算法