解题思路
这是一个典型的贪心算法,基本思路就是:扫描字符串数组,累加长度,当发现长度超过最大长度的时候,就把前面的几个字符串按规则组合,加入到List中。
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> 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<String> result )
{
if(words==null||words.length==0)
return;
int sum = words[0].length();
int i;
for (i=1;i<words.length;i++)
{
sum += (words[i].length()+1);
if(sum>maxWidth)
break;
}
if(sum<=maxWidth)
{
String re = "";
if (words.length==1)
{
re += words[0];
for (int j=0;j<maxWidth-words[0].length();j++)
re += " ";
result.add(re);
return;
}
int len = 0;
for (int j=0;j<words.length-1;j++)
{
len += (words[j].length()+1);
re += words[j];
re += " ";
}
re += words[words.length-1];
len += words[words.length-1].length();
for (int j =0;j<maxWidth-len;j++)
re += " ";
result.add(re);
return;
}
String[] s1 = Arrays.copyOfRange(words,0,i);
String[] s2 = Arrays.copyOfRange(words,i,words.length);
result.add(mergeString(s1,maxWidth));
greedy(s2,maxWidth,result);
}
public String mergeString(String[] words,int maxWidth)
{
String result = "";
int sum = 0;
for(int i=0;i<words.length;i++)
sum += words[i].length();
if (words.length==1)
{
result += words[0];
for (int i=0;i<maxWidth-words[0].length();i++)
result += " ";
return result;
}
int meanSpace = (maxWidth-sum)/(words.length-1);
int moreSpace = (maxWidth-sum)%(words.length-1);
for (int i=0;i<words.length-1;i++)
{
result += words[i];
for (int j=0;j<meanSpace;j++)
result += " ";
if(moreSpace>0)
{
result += " ";
moreSpace--;
}
}
result += words[words.length-1];
return result;
}