leetCode68. 文本左右对齐

基本思路:
leetCode68. 文本左右对齐


代码

cpp 复制代码
class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        vector<string> res;
        for(int i = 0; i < words.size(); i++){ // 枚举有多少个单词
            int j = i + 1; // j表示各单词的下标
            int len = words[i].size(); // 该单词的长度
            // 看当前行可以放多少个单词
            // 当前单词长度 + 1个空格 + 下一个单词的长度 <= maxwidth,表示改行还可以继续放
            while(j < words.size() && len + 1 + words[j].size() <= maxWidth){
                len += 1 + words[j++].size();
            }

            string line = "";
            if(j == words.size() || j == i + 1){
                // 当j是在最后的位置,或者当前行只有一个单词,进行左对齐
                line += words[i];
                for(int k = i + 1; k < j; k++){
                    line += ' ' + words[k];
                }

                while(line.size() < maxWidth) line += ' ';
            }else{ // 进行的是左右对齐
                int cnt = j - i - 1; //空隙的数量 = 单词的数量(j - i)- 1
                int r = maxWidth - len + cnt; // 总共的空格数量
                line += words[i];

                int k = 0;// 表示从第一个空隙开始计算
                while(k < r % cnt) { // 除不尽,r%cnt !=0,则前r%cnt个间隙r/cnt+1个空格,最后一个间隙r/cnt个空格
                    line += string(r / cnt + 1, ' ') + words[i + k + 1];
                    k++;
                }
                while(k < cnt) {// 这里加while是因为如果能整除,r%cnt=0,则全部为r/cnt个空格,对于每个cnt间隙内
                    line += string(r / cnt, ' ') + words[i + k + 1];
                    k++;
                }
            }

            res.push_back(line);
            i = j - 1;
        }

        return res;
    }
};
相关推荐
im_AMBER3 小时前
Leetcode 160 最小覆盖子串 | 串联所有单词的子串
开发语言·javascript·数据结构·算法·leetcode
帅小伙―苏4 小时前
力扣483找到字符串中所有字母异位词
算法·leetcode
smj2302_796826525 小时前
解决leetcode第3906题统计网格路径中好整数的数目
python·算法·leetcode
KobeSacre5 小时前
leetcode 树
算法·leetcode·职场和发展
大大杰哥6 小时前
leetcode hot100(1) 哈希
leetcode
Engineer邓祥浩6 小时前
LeetCode 热题 100 - 第1题:两数之和
算法·leetcode·职场和发展
阿Y加油吧6 小时前
算法二刷复盘:LeetCode 79 单词搜索 & 131 分割回文串(Java 回溯精讲)
java·算法·leetcode
6Hzlia6 小时前
【Hot 100 刷题计划】 LeetCode 101. 对称二叉树 | C++ DFS 极简递归模板
c++·leetcode·深度优先
北顾笙9806 小时前
day30-数据结构力扣
数据结构·算法·leetcode
承渊政道8 小时前
【递归、搜索与回溯算法】(掌握记忆化搜索的核心套路)
数据结构·c++·算法·leetcode·macos·动态规划·宽度优先