Thursday, October 29, 2015

Leetcode: 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 Lcharacters.
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."]
L16.
Return the formatted lines as:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]
Note: Each word is guaranteed not to exceed L in length.
Corner Cases:
  • A line other than the last line might contain only one word. What should you do in this case?
    In this case, that line should be left-justified.
Understand the problem:
The problem can be divided into two parts. The first part is to determine how many words can form in a line. Then the second part is to determine the length of white spaces between words. 

For the first part, since there must be at least one white space between each word, we can count the total length including one white space until the length is greater than the L. There is one corner case to consider: the last line where the total length might be smaller than L. 

For the second part, again, there are two cases to consider:
 -- If it is the last line, or if the line contains only one word. For this case, the line should be left-justified. 
-- Otherwise, we could calculate how many white spaces we should have, and divided by number of slots between words. 

Code (Java):
public class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {
        List<String> result = new ArrayList<>();
        if (words == null || words.length == 0 || maxWidth < 0) {
            return result;
        }
        
        if (maxWidth == 0) {
            result.add("");
            return result;
        }
        
        fullJustifyHelper(0, words, result, maxWidth);
        
        return result;
    }
    
    private void fullJustifyHelper(int start, String[] words, 
                  List<String> result, int L) {
        if (start >= words.length) {
            return;
        }
        
        int total = 0;
        int len = 0;
        int next = -1;
        int i = start;
        
        while (i < words.length && total < L) {
            total += words[i].length();
            
            if (total > L) {
                next = i;
                break;
            }
            
            len += words[i].length();
            total++;
            i++;
        }
        
        if (next == -1) {
            next = i;
        }
        
        addLists(words, start, next, result, len, L);
        
        fullJustifyHelper(next, words, result, L);
    }
    
    private void addLists(String[] words, int start, int next, 
                          List<String> result, int len, int L) {
        int slots = next - start - 1;
        StringBuffer sb = new StringBuffer();
        // Last line or only one word in a line
        if (slots == 0 || next == words.length) {
            for (int i = start; i < next; i++) {
                sb.append(words[i]);
                if (i == next - 1) {
                    break;
                }
                sb.append(" ");
            }
            
            int trailingSpace = L - len - slots;
            for (int i = 0; i < trailingSpace; i++) {
                sb.append(" ");
            }
            
            result.add(sb.toString());
        } else {
            int aveSpace = (L - len) / slots;
            int moreSpace = (L - len) % slots;
            for (int i = start; i < next; i++) {
                sb.append(words[i]);
                if (i == next - 1) {
                    break;
                }
                for (int j = 0; j < aveSpace; j++) {
                    sb.append(" ");
                }
                
                if (moreSpace > 0) {
                    sb.append(" ");
                    moreSpace--;
                }
            }   
            result.add(sb.toString());
        }
    }
}


2 comments:

  1. Hi, firstly thanks for sharing this. I used this code for printing text in justified format. Recently encountered StackOverflowError because of recursive calls. Also, this particular case arise when there are multiple special characters in the text e.g. *** ### etc.

    Try this : (maxwidth = 44)
    Exchange policy: Sold goods can be exchanged with in 5 working days.

    *Note: No exchange on inner wear because to maintain hygiene.

    ******Follow us on******

    Instagram: @Abcdefg.Hijklmno

    Facebook: Abcdefg.Hijklmno #pqrstuvw

    WhatsApp: +00 00000 00000
    ***************

    ReplyDelete