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;
    }
};
相关推荐
java_nnnn13 小时前
LeetCode刷题滑动窗口(水果成篮+找到字符串中所有字母的异位词)Java
java·开发语言·leetcode
文丑颜不良啊16 小时前
LeetCode276~300题目解析
java·leetcode
傅科摆 _ py18 小时前
链表力扣复习
数据结构·leetcode·链表
圣保罗的大教堂21 小时前
leetcode 3863. 将一个字符串排序的最小操作次数 中等
leetcode
Tisfy21 小时前
LeetCode 3863.将一个字符串排序的最小操作次数:分类讨论(一次遍历)——简单易懂版
算法·leetcode·字符串·题解·分类讨论
0+11121 小时前
算法 --递归
算法·leetcode
y1su1 天前
Leetcode 链表,树,回溯 模板
java·leetcode·链表
文丑颜不良啊1 天前
LeetCode201~225题目解析
java·leetcode
Nil2082 天前
LeetCode 283移动零
数据结构·算法·leetcode
文丑颜不良啊2 天前
LeetCode226~250题目解析
java·leetcode