Justified Text

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.

Your program should return a list of strings, where each string represents a single line.

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.

Method:

We first figure out which words we can put on each line, and then assign spaces accordingly. Don't forget to do padding if there is not enough space on the right.

Solution:

Time: O(m * n)
Space: O(m * n)

public class Solution {
    public ArrayList<String> fullJustify(ArrayList<String> A, int B) {
        ArrayList<String> result = new ArrayList<>();
        if (A == null || A.size() == 0) return result;
        StringBuilder sb = new StringBuilder();
        int i = 0;
        List<String> curr = new ArrayList<>();
        int currSize = 0;
        while (i < A.size()) {
            String str = A.get(i);
            if (currSize == 0 || (currSize + str.length() + curr.size()) <= B) {
                curr.add(str);
                currSize += str.length();
                i ++;
            } else {
                int gap = B - currSize;
                int numberOfSpaceEachWord = curr.size() > 1 ? gap / (curr.size() - 1) : 0;
                int numberOfSpaceLeft = curr.size() > 1 ? gap - numberOfSpaceEachWord * (curr.size() - 1) : 0;
                for (int j = 0; j < curr.size() - 1; j ++) {
                    String s = curr.get(j);
                    sb.append(s);
                    for (int k = 0; k < numberOfSpaceEachWord; k ++) {
                        sb.append(' ');
                    }
                    if (numberOfSpaceLeft > 0) {
                        sb.append(' ');
                        numberOfSpaceLeft --;
                    }
                }
                sb.append(curr.get(curr.size() - 1));
                while (sb.length() < B) {
                    sb.append(' ');
                }
                result.add(sb.toString());
                curr.clear();
                currSize = 0;
                sb.setLength(0);
            }
        }
        if (curr.size() > 0) {
            for (int j = 0; j < curr.size() - 1; j ++) {
                String s = curr.get(j);
                sb.append(s);
                sb.append(' ');
            }
            sb.append(curr.get(curr.size() - 1));
            while (sb.length() < B) {
                sb.append(' ');
            }
            result.add(sb.toString());
        }
        return result;
    }
}

class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {
        List<List<String>> lines = new ArrayList<>();
        Map<Integer, Integer> lineToLength = new HashMap<>();
        lines.add(new ArrayList<>());
        int curWordsLength = 0;
        for (int i = 0; i < words.length; i ++) {
            int line = lines.size() - 1;
            List<String> curLine = lines.get(line);
            int spacesInCurrLine = curLine.size();
            String curWord = words[i];
            if (curWordsLength + spacesInCurrLine + curWord.length() <= maxWidth) {
                curLine.add(curWord);
                curWordsLength += curWord.length();
            } else {
                List<String> newLine = new ArrayList<>();
                line ++;
                newLine.add(curWord);
                curWordsLength = curWord.length();
                lines.add(newLine);
            }
            lineToLength.put(line, curWordsLength);
        }
        List<String> result = new ArrayList<>();
        for (int i = 0; i < lines.size(); i ++) {
            List<String> line = lines.get(i);
            StringBuilder sb = new StringBuilder();
            int numSpace = Math.max(1, line.size() - 1);
            int commonSpace = (maxWidth - lineToLength.get(i)) / numSpace;
            int leftOverSpace = maxWidth - lineToLength.get(i) - commonSpace * numSpace;
            for (int j = 0; j < line.size(); j ++) {
                sb.append(line.get(j));
                if (i == lines.size() - 1) {
                    commonSpace = 1;
                    leftOverSpace = 0;
                }
                if (j == line.size() - 1) continue;
                for (int k = 0; k < commonSpace; k ++) {
                    sb.append(" ");
                }
                if (leftOverSpace > 0) {
                    sb.append(" ");
                    leftOverSpace --;
                }
            }
            while (sb.length() < maxWidth) {
                sb.append(" ");
            }
            result.add(sb.toString());
        }
        return result;
    }
}