推荐一个详解:作者:ikaruga
链接:https://leetcode-cn.com/problems/text-justification/solution/text-justification-by-ikaruga/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
底下评论里有个java版本的,还有注释,推荐去看看。
个人微改:
import java.util.ArrayList;
import java.util.List;
class Text{
List<String> resList = new ArrayList<>();
public List<String> fullJustify(String[] words,int maxWidth){
int left = 0,lenW = words.length;
while(left<lenW) {
int right = findRight(words,maxWidth,left);
if(right==lenW-1){
resList.add(fillWords(words,maxWidth,left,right,true));
}else{
resList.add(fillWords(words,maxWidth,left,right,false));
}
left = right + 1;
}
return resList;
}
public String fillWords(String[] words,int maxWidth,int left,int right,boolean isLastLine) {
int wordNums = right - left + 1;
int spaceCount = maxWidth + 1 - wordNums;
for(int i=left;i<=right;i++) {
spaceCount -= words[i].length();
}
int spaceSuffix = 1;
int spaceAvg = (wordNums==1)?1:spaceCount/(wordNums-1);
int spaceExtra = (wordNums==1)?0:spaceCount%(wordNums-1);
StringBuilder sb = new StringBuilder();
for(int i=left;i<right;i++) {
sb.append(words[i]);
if(isLastLine) {
sb.append(" ");
continue;
}
int sum = spaceSuffix + spaceAvg + ((i-left)<spaceExtra?1:0);
while(sum-->0) {sb.append(" ");}
}
sb.append(words[right]);
int sum = maxWidth - sb.length();
while(sum-->0) {sb.append(" ");}
return sb.toString();
}
public int findRight(String[] words,int maxWidth,int left) {
int right = left+1;
int countWord = words[left].length();
while(right<words.length && (countWord+words[right].length()+1)<=maxWidth) {
countWord += words[right].length()+1;
right++;
}
return right-1;
}
}
public class TextJustification {
public static void main(String args[]) {
String[] words = new String[] {"This", "is", "an", "example", "of", "text", "justification."};
Text hah = new Text();
System.out.println(hah.fullJustify(words,16).toString());
}
}

本文详细介绍了如何使用Java解决LeetCode上的文本 justification问题,通过实例演示了如何根据最大宽度合理分配单词并保持格式。
171万+

被折叠的 条评论
为什么被折叠?



