每日一练_94(2021.9.11) 文本左右对齐(leetcode)。

本文详细介绍了如何使用Java解决LeetCode上的文本 justification问题,通过实例演示了如何根据最大宽度合理分配单词并保持格式。

推荐一个详解:作者:ikaruga
链接:https://leetcode-cn.com/problems/text-justification/solution/text-justification-by-ikaruga/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

底下评论里有个java版本的,还有注释,推荐去看看。

个人微改:

import java.util.ArrayList;
import java.util.List;

class Text{
    
    List<String> resList = new ArrayList<>();
    
    public List<String> fullJustify(String[] words,int maxWidth){
        int left = 0,lenW = words.length;
        while(left<lenW) {
            int right = findRight(words,maxWidth,left);
            if(right==lenW-1){
                resList.add(fillWords(words,maxWidth,left,right,true));
            }else{
                resList.add(fillWords(words,maxWidth,left,right,false));
            }
            left = right + 1;
        }
        return resList;
    }
    
    public String fillWords(String[] words,int maxWidth,int left,int right,boolean isLastLine) {
        int wordNums = right - left + 1;
        int spaceCount = maxWidth + 1 - wordNums;
        for(int i=left;i<=right;i++) {
            spaceCount -= words[i].length();
        }
        int spaceSuffix = 1;
        int spaceAvg = (wordNums==1)?1:spaceCount/(wordNums-1);
        int spaceExtra = (wordNums==1)?0:spaceCount%(wordNums-1);
        
        StringBuilder sb = new StringBuilder();
        for(int i=left;i<right;i++) {
            sb.append(words[i]);
            if(isLastLine) {
                sb.append(" ");
                continue;
            }
            int sum = spaceSuffix + spaceAvg + ((i-left)<spaceExtra?1:0);
            while(sum-->0) {sb.append(" ");}
        }
        sb.append(words[right]);
        int sum = maxWidth - sb.length();
        while(sum-->0) {sb.append(" ");}
        return sb.toString();
    }
    
    public int findRight(String[] words,int maxWidth,int left) {
        int right = left+1;
        int countWord = words[left].length();
        while(right<words.length && (countWord+words[right].length()+1)<=maxWidth) {
            countWord += words[right].length()+1;
            right++;
        }
        return right-1;
    }
}
public class TextJustification {
    public static void main(String args[]) {
        String[] words = new String[] {"This", "is", "an", "example", "of", "text", "justification."};
        Text hah = new Text();
        System.out.println(hah.fullJustify(words,16).toString());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是壮壮没错了丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值