博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java for LeetCode 068 Text Justification
阅读量:5335 次
发布时间:2019-06-15

本文共 2013 字,大约阅读时间需要 6 分钟。

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.

解题思路:

直接按照约束条件老实实现即可,JAVA实现如下:

static public List
fullJustify(String[] words, int maxWidth) { List
list=new ArrayList
(); int start=0,end=-1,sum=0; for(int i=0;i
maxWidth){ i--; start=end+1; end=i; sum=0; list.add(oneString(words,start,end,maxWidth)); continue; } sum++; } if(sum>0) list.add(oneString(words,end+1,words.length-1,maxWidth)); return list; } static public String oneString(String[] words,int start,int end,int maxWidth){ StringBuilder sb=new StringBuilder(); if(start==end) sb.append(words[start]); else if(end==words.length-1){ for(int i=start;i<=end-1;i++) sb.append(words[i]+" "); sb.append(words[end]); } else{ int spaceSum=maxWidth; for(int i=start;i<=end;i++) spaceSum-=words[i].length(); int extra=spaceSum-(spaceSum/(end-start))*(end-start); for(int i=start;i<=end;i++){ sb.append(words[i]); for(int j=0;j
0) sb.append(" "); } } while(sb.length()

 

转载于:https://www.cnblogs.com/tonyluis/p/4508338.html

你可能感兴趣的文章
零散笔记
查看>>
子父类不同属性代码执行顺序
查看>>
dbcp 1.4 底层连接断开时内存泄露bug
查看>>
关于密码
查看>>
ASP.NET 导出PPT
查看>>
Git忽略规则及.gitignore规则不生效的解决办法
查看>>
How to fix the sources list
查看>>
Eclipse的数据库插件
查看>>
mysql简单学习
查看>>
嵌入式操作系统
查看>>
URI和URL的区别
查看>>
UI---startup--jquery
查看>>
echart使用总结
查看>>
TCP协议中的三次握手和四次挥手(图解)
查看>>
更改Win10用户名为英文,还有一些善后
查看>>
第1章2节《MonkeyRunner源码剖析》概述:边界(原创)
查看>>
android:layout_gravity和android:gravity的区别
查看>>
Spring事务管理(详解+实例)
查看>>
aix转移lv大小到其它磁盘
查看>>
JS实现上传图片的三种方法并实现预览图片功能
查看>>