68. Text Justification

解题思路

这是一个典型的贪心算法,基本思路就是:扫描字符串数组,累加长度,当发现长度超过最大长度的时候,就把前面的几个字符串按规则组合,加入到List中。

 public List fullJustify(String[] words, int maxWidth) {
        List result = new ArrayList<>();
        if(words==null||words.length==0)
            return result;
        if(maxWidth==0)
        {
            result.add("");
            return result;

        }
        greedy(words,maxWidth,result);
        return result;

    }
    public void greedy(String[] words,int maxWidth,List result )
    {
        if(words==null||words.length==0)
            return;
        int sum = words[0].length();
        int i;
        for (i=1;imaxWidth)
                break;
        }
        if(sum<=maxWidth)
        {
            String re = "";

            if (words.length==1)
            {
                re += words[0];
                for (int j=0;j0)
            {
                result += " ";
                moreSpace--;
            }
        }
        result += words[words.length-1];
        return  result;
    }

你可能感兴趣的:(68. Text Justification)