Text Justification -- LeetCode

原标题链接: http://oj.leetcode.com/problems/text-justification/ 
这道题属于纯粹的字符串操作。要把一串单词安排成多行限定长度的字符串。主要难点在于空格的安排,首先每一个单词之间必须有空格隔开。而当当前行放不下很多其它的单词而且字符又不能填满长度L时。我们要把空格均匀的填充在单词之间。假设剩余的空格量刚好是间隔倍数那么就均匀分配就可以。否则还必须把多的一个空格放到前面的间隔里面。实现中我们维护一个count计数记录当前长度。超过之后我们计算共同的空格量以及多出一个的空格量,然后将当行字符串构造出来。最后一个细节就是最后一行不须要均匀分配空格。句尾留空就能够。所以要单独处理一下。时间上我们须要扫描单词一遍,然后在找到行尾的时候在扫描一遍当前行的单词,只是整体每一个单词不会被訪问超过两遍,所以整体时间复杂度是O(n)。而空间复杂度则是结果的大小(跟单词数量和长度有关,不能准确定义,假设知道最后行数r。则是O(r*L))。代码例如以下: 
public ArrayList<String> fullJustify(String[] words, int L) {
    ArrayList<String> res = new ArrayList<String>();
    if(words==null || words.length==0)
        return res;
    int count = 0;
    int last = 0;
    for(int i=0;i<words.length;i++)
    {
        if(count+words[i].length()+(i-last)>L)
        {
            int spaceNum = 0;
            int extraNum = 0;
            if(i-last-1>0)
            {
                spaceNum = (L-count)/(i-last-1);
                extraNum = (L-count)%(i-last-1);
            }
            StringBuilder str = new StringBuilder();
            for(int j=last;j<i;j++)
            {
                str.append(words[j]);
                if(j<i-1)
                {
                    for(int k=0;k<spaceNum;k++)
                    {
                        str.append(" ");
                    }
                    if(extraNum>0)
                    {
                        str.append(" ");
                    }
                    extraNum--;
                }
            }
            for(int j=str.length();j<L;j++)
            {
                str.append(" ");
            }       
            res.add(str.toString());
            count=0;
            last=i;
        }
        count += words[i].length();
    }
    StringBuilder str = new StringBuilder();
    for(int i=last;i<words.length;i++)
    {
        str.append(words[i]);
        if(str.length()<L)
            str.append(" ");
    }
    for(int i=str.length();i<L;i++)
    {
        str.append(" ");
    }
    res.add(str.toString());
    return res;
}
这道题属于那种文本编辑的子操作之类的题目,从算法思路上没有什么特别。不过还是相当多的实现细节,别easy在第一时间,你可能想练习几次哈。

版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/yxwkf/p/4715192.html