力扣68. 文本左右对齐(java)

public class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {
        List<List<String>> res = new ArrayList<>();
        List<String> temp1 = new ArrayList<>();
        int len = 0;
        for (String word : words) {
            len = len + word.length() + 1;
            if (len - 1 > maxWidth) {
                res.add(temp1);
                len = word.length() + 1;
                temp1 = new ArrayList<>();
            }
            temp1.add(word);
        }
        res.add(temp1);//先把每一行的单词取出来

        List<String> result = new ArrayList<>();
        for (int j=0;j<res.size()-1;j++) {
            List<String> templist = res.get(j);
            String temp = "";
            int l = templist.size();
            if (l == 1) {
                String tempstr = templist.get(0);
                temp += tempstr;
                while (temp.length() != maxWidth) {
                    temp += " ";
                }
            } else {
                int sum = 0;
                for (String word : templist) {
                    sum += word.length();
                }
                int spaces = maxWidth - sum;//空格的总数量
                int space = spaces / (l - 1);//加入空格的数量
                int remain = spaces - space * (l - 1);//见下面具体解释

                String blank = "";
                for (int i = 0; i < space; i++) {
                    blank += " ";//加入的空格字符串
                }
                for (int i = 0; i < remain; i++) {//见下面具体解释
                    temp += templist.get(i);
                    temp += blank;
                    temp += " ";
                }
                for (int i = remain; i < l - 1; i++) {
                    temp += templist.get(i);
                    temp += blank;
                }
                temp += templist.get(l - 1);
            }
            result.add(temp);
        }
        //最后一行左对齐,单独处理
        List<String> templist = res.get(res.size()-1);
        String temp = "";
        for(String word:templist){
            temp += word;
            temp +=" ";
        }if(temp.length()>maxWidth){//如果多加了一个空格,就把这个多加的空格删掉
            temp = temp.substring(0,temp.length()-1);
        }while(temp.length()<maxWidth){
            temp +=" ";
        }
        result.add(temp);
        return result;
    }

具体解释:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值