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;
    }
};
相关推荐
chao_7891 小时前
链表题解——环形链表 II【LeetCode】
数据结构·leetcode·链表
岁忧4 小时前
LeetCode 高频 SQL 50 题(基础版)之 【高级字符串函数 / 正则表达式 / 子句】· 上
sql·算法·leetcode
eachin_z5 小时前
力扣刷题(第四十九天)
算法·leetcode·职场和发展
飞川撸码7 小时前
【LeetCode 热题100】网格路径类 DP 系列题:不同路径 & 最小路径和(力扣62 / 64 )(Go语言版)
算法·leetcode·golang·动态规划
_Itachi__15 小时前
LeetCode 热题 100 74. 搜索二维矩阵
算法·leetcode·矩阵
chao_78916 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
编程绿豆侠19 小时前
力扣HOT100之多维动态规划:1143. 最长公共子序列
算法·leetcode·动态规划
dying_man1 天前
LeetCode--24.两两交换链表中的结点
算法·leetcode
yours_Gabriel1 天前
【力扣】2434.使用机器人打印字典序最小的字符串
算法·leetcode·贪心算法