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;
    }
};
相关推荐
旖旎夜光42 分钟前
LeetCode 238:除自身以外数组的乘积(前缀和) —— 题解
数据结构·c++·算法·leetcode·前缀和
学习星球13 小时前
单调栈——从“找下一个更大的“到柱状图中的最大矩形
数据库·c++·算法·leetcode·xcode
血小板要健康17 小时前
网格 dfs 与 FloodFill:从岛屿、区域到搜索路径
笔记·算法·leetcode·深度优先
鹿角片ljp21 小时前
LeetCode 141. 环形链表|从 HashSet 到快慢指针 O (1) 空间最优解
算法·leetcode·链表
ZC跨境爬虫1 天前
LeetCode 219. 存在重复元素 II(滑动窗口 + 哈希表详解)
算法·leetcode·散列表
吞下星星的少年·-·1 天前
The 2025 ICPC Asia East Continent Online Contest (I) A题(模拟+贪心)
算法·贪心·模拟
Navigator_Z1 天前
LeetCode //C - 1220. Count Vowels Permutation
c语言·算法·leetcode
feilieren1 天前
leetcode - 389. 找不同
算法·leetcode
evans在进步1 天前
LeetCode 238 除自身以外数组的乘积:前缀积与后缀积详解
算法·leetcode·职场和发展
刃神太酷啦1 天前
Linux 系统 MySQL 完整安装配置教程:从卸载 MariaDB 到优化 my.cnf----《Hello MySQL!》(1)
android·linux·c语言·c++·mysql·leetcode·mariadb