Text Justification
来源:互联网 发布:plc编程难吗 编辑:程序博客网 时间:2024/05/23 10:12
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. " ]
Note: Each word is guaranteed not to exceed L in length.
public class Solution { public List<String> fullJustify(String[] words, int maxWidth) { ArrayList<String> result = new ArrayList<String>();int len=words.length,curLen=0,lastI=0;for(int i=0;i<=len;i++){if(i==len||curLen+words[i].length()+i-lastI>maxWidth){StringBuffer buf=new StringBuffer();int spaceLen=maxWidth-curLen;int spaceSlots=i-lastI-1;if(spaceSlots==0||i==len){for(int j=lastI;j<i;j++){buf.append(words[j]);if(j!=i-1)appendSpace(buf, 1);}appendSpace(buf, maxWidth-buf.length());}else {int spaceEach=spaceLen/spaceSlots;int sapceExtra=spaceLen%spaceSlots;for(int j=lastI;j<i;j++){buf.append(words[j]);if(j!=i-1)appendSpace(buf, spaceEach+(j-lastI<sapceExtra?1:0));}}result.add(buf.toString());lastI=i;curLen=0;}if(i<len)curLen+=words[i].length();}return result; } private void appendSpace(StringBuffer sb, int count) { for (int i = 0; i < count; i++) sb.append(' '); }}
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Pinyin4j的基本用法
- 一些前端的心得体会,笔记
- Spring的Bean的生命周期
- C++中指针和引用的区别与联系
- hdu-1509 Windows Message Queue(优先队列)
- Text Justification
- 点击事件在XML标签属性中声明
- 程序开发的23种模式
- hdu 5323 Solve this interesting problem(15多校第三场1008)(暴力)
- 小马哥-----高仿米2 米4版本新版机型版本较多 刷机警惕 8219 8213 7220 7219 L9007 8221 等机型版本
- C++对象内存布局(1)
- Android如何实现侧拉栏
- C#委托
- XHTML基础