Text Justification

`String`

Hard

Solution & Analysis

@Grandyang 将这道题翻译为文本的左右对齐是因为这道题像极了word软件里面的文本左右对齐功能

@mnmunknown

``````public class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> list = new ArrayList<String>();

int N = words.length;
int right = 0;
for(int left = 0; left < N; left = right){
// Each word comes with one space;
int len = -1;
for(right = left; right < N && len + words[right].length() + 1 <= maxWidth; right ++){
len += words[right].length() + 1;
}

// Those are in case there's only one word picked, or in last line
int space = 1;
int extra = 0;
if(right != left + 1 && right != N){
// right - left - 1 is number of gaps
space = (maxWidth - len) / (right - left - 1) + 1;
extra = (maxWidth - len) % (right - left - 1);
}
StringBuilder sb = new StringBuilder(words[left]);
for(int i = left + 1; i < right; i++){
for(int j = 0; j < space; j++) sb.append(' ');
if(extra-- > 0) sb.append(' ');
sb.append(words[i]);
}

int rightSpace = maxWidth - sb.length();
while(rightSpace-- > 0) sb.append(' ');
}

return list;
}
}``````

@programcreek

https://www.programcreek.com/2014/05/leetcode-text-justification-java/

There is not a special algorithm required to solve this problem. To correctly solve this problem, the following situations should be taken care of:

1. if a line has only one word and the word's length is less than max width, we need to fill the left part with spaces.

2. how to distribute extra spaces for each words when the number of spaces can not be evenly distributed to each word.

``````public List<String> fullJustify(String[] words, int maxWidth) {
List<String> result = new ArrayList<String>();

if(words==null || words.length==0){
return result;
}

int count=0;
int last=0;
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<words.length; i++){
count = count + words[i].length();

if(count+i-last>maxWidth){
int wordsLen = count-words[i].length();
int spaceLen = maxWidth-wordsLen;
int eachLen = 1;
int extraLen = 0;

if(i-last-1>0){
eachLen = spaceLen/(i-last-1);
extraLen = spaceLen%(i-last-1);
}

StringBuilder sb = new StringBuilder();

for(int k=last; k<i-1; k++){
sb.append(words[k]);

int ce = 0;
while(ce<eachLen){
sb.append(" ");
ce++;
}

if(extraLen>0){
sb.append(" ");
extraLen--;
}
}

sb.append(words[i-1]);//last words in the line
//if only one word in this line, need to fill left with space
while(sb.length()<maxWidth){
sb.append(" ");
}

last = i;
count=words[i].length();
}
}

int lastLen = 0;
StringBuilder sb = new StringBuilder();

for(int i=last; i<words.length-1; i++){
count = count+words[i].length();
sb.append(words[i]+" ");
}

sb.append(words[words.length-1]);
int d=0;
while(sb.length()<maxWidth){
sb.append(" ");
}