From e89cc7971670425c466e05ab19e592573e4994f9 Mon Sep 17 00:00:00 2001 From: fleyx Date: Thu, 4 Jan 2024 18:12:43 +0800 Subject: [PATCH] add --- 5.leetcode/src/com/fanxb/common/Q68.java | 33 ++++++++++++++++++++---- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/5.leetcode/src/com/fanxb/common/Q68.java b/5.leetcode/src/com/fanxb/common/Q68.java index fdd4d34..b475ca9 100644 --- a/5.leetcode/src/com/fanxb/common/Q68.java +++ b/5.leetcode/src/com/fanxb/common/Q68.java @@ -1,6 +1,7 @@ package com.fanxb.common; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; /** @@ -11,20 +12,42 @@ import java.util.List; */ public class Q68 { public List fullJustify(String[] words, int maxWidth) { - int length = words.length, int leftWidth = maxWidth; - List lineWord = new ArrayList<>(); + int length = words.length, leftWidth = maxWidth; + List lineWord = new LinkedList<>(); + List> lineList = new LinkedList<>(); for (int i = 0; i < length; i++) { if (lineWord.isEmpty()) { lineWord.add(words[i]); leftWidth -= words[i].length(); } else { - if (leftWidth >= words[i].length() + 1){ + if (leftWidth >= words[i].length() + 1) { //可以放下 - }else{ - //hao + lineWord.add(words[i]); + leftWidth -= words[i].length() + 1; + } else { + //放不下了,需要新开一行 + lineList.add(lineWord); + lineWord = new LinkedList<>(); + leftWidth = maxWidth; } } } + List res = new ArrayList<>(lineList.size()); + for (int i = 0; i < lineList.size() - 1; i++) { + addToRes(res, lineList.get(i), false); + } + addToRes(res, lineList.get(lineList.size() - 1), true); + return res; + } + + private void addToRes(List res, List line, boolean lastLine) { + StringBuilder temp = new StringBuilder(); + temp.append(line.get(0)); + if (lastLine) { + for (int i = 1; i < line.size(); i++) temp.append(' ').append(line.get(i)); + } else { + + } } public static void main(String[] args) {