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;
    }
};
相关推荐
熬了夜的程序员2 小时前
【LeetCode】89. 格雷编码
算法·leetcode·链表·职场和发展·矩阵
dragoooon344 小时前
[优选算法专题四.前缀和——NO.31~32 连续数组、矩阵区域和]
数据结构·算法·leetcode·1024程序员节
熬了夜的程序员7 小时前
【LeetCode】87. 扰乱字符串
算法·leetcode·职场和发展·排序算法
·白小白10 小时前
力扣(LeetCode) ——15.三数之和(C++)
c++·算法·leetcode
海琴烟Sunshine10 小时前
leetcode 268. 丢失的数字 python
python·算法·leetcode
仰泳的熊猫11 小时前
LeetCode:268. 丢失的数字
数据结构·c++·算法·leetcode
VT.馒头11 小时前
【力扣】2725. 间隔取消
javascript·leetcode·1024程序员节
咪咪渝粮14 小时前
108. 将有序数组转换为二叉搜索树
算法·leetcode
仰泳的熊猫14 小时前
LeetCode:1905. 统计子岛屿
数据结构·c++·算法·leetcode
熬了夜的程序员16 小时前
【LeetCode】88. 合并两个有序数组
数据结构·算法·leetcode·职场和发展·深度优先