【leetcode】68.(Hard) Text Justification
阿新 • • 發佈:2018-11-19
提交程式碼:
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> res=new ArrayList<String>();
int startIndex=0,endIndex=0,curWidth;
while(endIndex<words.length) {
curWidth=0;
curWidth+=words[ endIndex].length();
endIndex++;
while(endIndex<words.length&&
curWidth+words[endIndex].length()<maxWidth) {
curWidth+=(words[endIndex].length()+1); //at least one space
endIndex++;
}
addString(startIndex,endIndex,words,maxWidth,res);
startIndex=endIndex;
endIndex=startIndex;
}
return res;
}
public void addString(int startIndex,int endIndex,String[] words,
int maxWidth,List<String> res) {
if((endIndex-startIndex)==1) {
//with one word in a line
String str="";
str+= words[startIndex];
for(int i=0;i<maxWidth-words[startIndex].length();i++)
str+=" ";
res.add(str);
return;
}else if(endIndex==words.length) {
//the last line should be left-justified
int totalSpaceWidth=maxWidth;
String str="";
str+=words[startIndex];
totalSpaceWidth-=words[startIndex].length();
for(int i=startIndex+1;i<endIndex;i++) {
str+=" ";
str+=words[i];
totalSpaceWidth-=words[i].length();
}
for(int i=0;i<(totalSpaceWidth-(endIndex-startIndex-1));i++)
str+=" ";
res.add(str);
return;
}else {
//general situation
int curWidth=0,remainSpaceWidth,spaceWidth;
int spaceCnt=endIndex-startIndex-1;
for(int i=startIndex;i<endIndex;i++)
curWidth+=words[i].length();
remainSpaceWidth=maxWidth-curWidth;
String str="";
str+=words[startIndex];
for(int i=startIndex+1;i<endIndex;i++) {
spaceWidth=(int) Math.ceil((double)remainSpaceWidth/(spaceCnt--));
for(int j=0;j<spaceWidth;j++)
str+=" ";
str+=words[i];
remainSpaceWidth-=spaceWidth;
}
res.add(str);
}
}
}
執行結果: