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;
    }
};
相关推荐
iAkuya11 分钟前
(leetcode)力扣100 26环状链表2(双指针)
算法·leetcode·链表
sin_hielo13 分钟前
leetcode 2402(双堆模拟,小根堆)
数据结构·算法·leetcode
Morwit23 分钟前
【力扣hot100】 312. 戳气球(区间dp)
c++·算法·leetcode
Q741_1471 小时前
C++ 栈 模拟 力扣 394. 字符串解码 每日一题 题解
c++·算法·leetcode·模拟·
雪花desu1 小时前
【Hot100-Java简单】:两数之和 (Two Sum) —— 从暴力枚举到哈希表的思维跃迁
java·数据结构·算法·leetcode·哈希表
YGGP1 小时前
【Golang】LeetCode 121. 买卖股票的最佳时机
算法·leetcode
YGGP2 小时前
【Golang】LeetCode 45. 跳跃游戏 II
算法·leetcode·游戏
YGGP2 小时前
【Golang】LeetCode 763. 划分字母区间
算法·leetcode
YGGP2 小时前
【Golang】LeetCode 1143. 最长公共子序列
算法·leetcode
Swift社区2 小时前
LeetCode 459 - 重复的子字符串
算法·leetcode·职场和发展