Text Justification

Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.

Return the formatted lines as:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]
Note: Each word is guaranteed not to exceed L in length.

Analysis

  • see code

Code

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

        //scan through all words
        for (int i=0, w; i<words.length;i=w){
            //determine how many words fit this line
            int len = -1; //1st word does not need space before it, so initialize with -1
            for (w=i; w < words.length && len+words[w].length()+1 <= maxWidth ;w++){
                len += (words[w].length() + 1);
            }

            //initialize a string from words[i] to words[w-1]
            StringBuilder sb = new StringBuilder(words[i]);

            //find space value between words
            //space: added space to each interval; extra: extra space for left intervals due to inbalance
            int space = 1, extra = 0;
            if (w!=i+1 && w!=words.length){//not one word, not last word
                space = (maxWidth - len)/(w-1-i)+1;
                extra = (maxWidth - len)%(w-1-i);
            } 

            //Example:
            //1st line: "This    is    an": i = 0, w = 3, len = 10, maxWidth = 16 
            //space = (16-10)/(3-1-0)+1 = 6/2+1 = 4
            //extra = (16-10)%(3-1-0) = 6%2 = 0
            //分别分配4个spaces到两个间隔中去,平均分,没有extra

            //buide string for this line
            //for line with only one word, this for loop will not be executed
            for (int j = i+1; j<w; j++){
                for (int s=0; s<space; s++) {sb.append(" ");}
                //尽量把extra往左边放,每个间隔多放一个
                if (extra-- > 0) sb.append(" ");
                sb.append(words[j]);
            }

            //add spaces for one word cases
            int strLen = maxWidth - sb.length();
            while (strLen-- >0) sb.append(" ");
            res. add(sb.toString());
        }

        return res;
    }
}

Reference

Leetcode