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(' ');    }}


0 0
原创粉丝点击