Text Justification

Text Justification

问题:

iven 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 exactlyL 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.

思路:

  手工模拟题

我的代码:

public class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {
        List<String> list = new ArrayList<String>();
        if(words==null || words.length==0)    return list;
        int i=0;
        while(i < words.length)
        {
            int start = i;
            int count = 0;
            for(; i<words.length; i++)
            {
                count += words[i].length() + 1;
                if(count > maxWidth+1) break;
            }
            int end = i-1;
            if(end == words.length-1)
            {
                StringBuffer tmp = new StringBuffer();
                int len = 0;
                for(int j=start; j<=end; j++)
                {
                    len += words[j].length()+1;
                    tmp.append(" "+words[j]);
                }
                if(len > maxWidth) list.add(tmp.toString().substring(1));
                else
                {
                    for(int k=len-1; k<maxWidth; k++)
                        tmp.append(" ");
                    list.add(tmp.toString().substring(1));
                }
            }
            else list.add(changeToString(start, end, words, maxWidth));
        }
        return list;
    }
    public String changeToString(int start, int end, String[] words, int maxWidth)
    {
        StringBuffer rst = new StringBuffer();
        int num = (end-start+1);
        if(num == 1)
        {
            rst.append(words[start]);
            for(int i=0; i< (maxWidth-words[start].length()); i++)
                rst.append(" ");
            return rst.toString();
        }
        int count = 0;
        for(int i=start; i<=end; i++)
            count += words[i].length();
        int avg = (maxWidth-count)/(num-1);
        int remain = (maxWidth-count)%(num-1);
        for(int j=start; j<end; j++)
        {
            rst.append(words[j]);
            for(int k=0; k<avg; k++)
                rst.append(" ");
            if(remain > 0)
            {
                rst.append(" ");
                remain--;
            }
        }
        rst.append(words[end]);
        return rst.toString();
    }
}
View Code

学习之处:

  • 这道题思路很简单,但是需要考虑的点还是很细的,只有一个字符的时候;除数为0的时候;最后一列单独来分析说明
  • 笔记本上没有eclipse,用的大脑调试的,竟然解决了,还不错,继续加油努力
  • 改变不好的习惯