面试经典150题——文本左右对齐

面试经典150题 day24

题目来源

力扣每日一题;题序:68

我的题解

方法一 模拟

分情况讨论

  1. 是最后一行 ------------将所有字符串先组合在一起,然后在末尾加空格
  2. 是单个单词一行 ------------ 将单个字符串先组合在一起,然后在末尾加空格
  3. 其他情况 -------------求均分的空格数avg和均分后还剩余的空格数ex,[left,left+ex+1)之间插入的空格数为 avg+1,[left+ex+1,right)之间插入空格数为 avg,注意:在两个范围之间还需要插入一个 avg的空格数
    时间复杂度 :O(m)。其中 m 是数组 words 中所有字符串的长度之和
    空间复杂度:O(m)
java 复制代码
public List<String> fullJustify(String[] words, int maxWidth) {
    List<String> res=new ArrayList<>();
    int n=words.length;
    for(int i=0;i<n;){
        int start=i;
        int end=start+1;
        //len记录当前行的使用字符串构成的新字符串的长度(现贪心,单词间只加一个空格)
        int len=words[start].length();
        while(end<n&&len+words[end].length()+1<=maxWidth){
            len+=words[end].length()+1;
            end++;
        }
        StringBuilder sb=new StringBuilder();
        //最后一行
        if(end==n){
            for(int j=start;j<end;j++){
                sb.append(words[j]);
                if(j!=end-1)
                    sb.append(' ');
            }
            insertSpace(sb,maxWidth-sb.length());
        //一行只有一个字符串
        }else if(start+1==end){
            sb.append(words[start]);
            insertSpace(sb,maxWidth-sb.length());
        }else{
            //在每两个字符之间加入1个空格后,还需要添加空格的数量
            int sub=maxWidth-len;
            //有多少个可以插入空格的位置
            int num=end-start-1;
            // 单词间实际需要插入的空格数(注意:这里是指右侧需要插入的空格数,左侧需要比右侧多1)
            int need=sub/num+1;
            //左侧应该有几个插入空格的地方
            int mod=sub%num;
            sb.append(words[start]);
            //先模拟左侧单词的加入
            for(int j=0;j<mod;j++){
                insertSpace(sb,need+1);
                sb.append(words[start+j+1]);
            }
            //再模拟右侧单词的加入
            for(int j=mod;j<num;j++){
                insertSpace(sb,need);
                sb.append(words[start+j+1]);
            }
        }
        res.add(sb.toString());
        i=end;
    }
    return res;
}

public void insertSpace(StringBuilder sb,int count){
    for(int i=0;i<count;i++){
        sb.append(" ");
    }
}

有任何问题,欢迎评论区交流,欢迎评论区提供其它解题思路(代码),也可以点个赞支持一下作者哈😄~

相关推荐
考虑考虑2 小时前
Java实现hmacsha1加密算法
java·后端·java ee
掉鱼的猫3 小时前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
java·spring boot
plainGeekDev3 小时前
广播接收器 → Flow + Lifecycle
android·java·kotlin
plainGeekDev3 小时前
EventBus → SharedFlow
android·java·kotlin
带刺的坐椅3 小时前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
java·springboot·web·solon
weedsfly3 小时前
还在用 Axios?你可能需要重新理解 XHR 与 Fetch
前端·javascript·面试
用户3721574261353 小时前
Java 将一个 PPT 文档拆分为多个文件
java
Hyyy5 小时前
什么是bun?和pnpm有什么区别
前端·面试·bun
To_OC13 小时前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
葫芦和十三14 小时前
图解 MongoDB 14|Cache 与淘汰:WiredTiger 的内存治理
后端·mongodb·面试