面试经典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(" ");
    }
}

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

相关推荐
AD钙奶-lalala1 小时前
Mac OS上搭建 http server
java
luckys.one2 小时前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
~|Bernard|3 小时前
在 PyCharm 里怎么“点鼠标”完成指令同样的运行操作
算法·conda
战术摸鱼大师4 小时前
电机控制(四)-级联PID控制器与参数整定(MATLAB&Simulink)
算法·matlab·运动控制·电机控制
Christo34 小时前
TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
人工智能·算法·机器学习·数据挖掘
好家伙VCC5 小时前
数学建模模型 全网最全 数学建模常见算法汇总 含代码分析讲解
大数据·嵌入式硬件·算法·数学建模
皮皮林5515 小时前
SpringBoot 全局/局部双模式 Gzip 压缩实战:14MB GeoJSON 秒变 3MB
java·spring boot
weixin_456904276 小时前
Spring Boot 用户管理系统
java·spring boot·后端
趁你还年轻_6 小时前
异步编程CompletionService
java