本文主要是介绍leetcode解题方案--068--Text Justification,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ’ ’ when necessary so that each line has exactly L characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is inserted between words.
For example,
words: [“This”, “is”, “an”, “example”, “of”, “text”, “justification.”]
L: 16.
Return the formatted lines as:
[
“This is an”,
“example of text”,
“justification. ”
]
分析
a waste of time
几个规则:
– 每个单词之间都有至少一个空格
– 尽量使空格均匀分
– 如果真的不能均分,那前面的空格大
– 最后一行不遵守以上准则
代码
class Solution {
public static List<String> fullJustify(String[] words, int maxWidth) {List<String> row = new LinkedList<>();List<String> ret = new LinkedList<>();if (words.length<1) {return ret;}int num = 0;for (int i = 0; i < words.length; i++) {if (num + 1 + words[i].length() <= maxWidth) {if (num != 0) {num++;}row.add(words[i]);num = num + words[i].length();} else {if (row.size()>0) {ret.add(getString(row, maxWidth, num-row.size()+1, false));}row.clear();num = 0;row.add(words[i]);num = num+words[i].length();}}if (row.size()!=0) {ret.add(getString(row, maxWidth, num-row.size()+1,true));}System.out.print(ret);return ret;}private static String getString(List<String> row, int maxWidth, int wordLength, boolean lastline) {StringBuffer sb = new StringBuffer("");int wordNum = row.size();if (lastline) {for (int p = 0;p<row.size()-1; p++) {sb.append(row.get(p));sb.append(" ");}sb.append(row.get(row.size()-1));int j = maxWidth-wordLength-row.size()+1;while (j-->0) {sb.append(" ");}return sb.toString();}if (wordNum>1) {int longSpace = (maxWidth-wordLength)%(wordNum-1);int space = (maxWidth-wordLength)/(wordNum-1);for (int p = 0;p<row.size()-1; p++) {sb.append(row.get(p));int j = space;while (j-->0) {sb.append(" ");}if (longSpace-->0) {sb.append(" ");}}sb.append(row.get(row.size()-1));}else {sb.append(row.get(0));int space = maxWidth -wordLength;while (space-->0) {sb.append(" ");}}System.out.print(sb.toString().length());return sb.toString();}
}
这篇关于leetcode解题方案--068--Text Justification的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!