Labels

Sunday, March 8, 2015

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.

Naive Way: The problem said "You should pack your words in a greedy approach". So I will pack the words greedily. Grad as many words as I can each time to form a line. To calculate the space, use an extra var to hold the remaining space after evenly distributes. For the last column, could assign an extra check.

Combining one word case and the last line case is feasible.

 public class Solution {  
   public List<String> fullJustify(String[] words, int L) {  
     List<String> list = new ArrayList<String>();  
     int i = 0;  
     while(i < words.length){  
       int j = i;  
       int len = 0;  
       // grab as many words as I can  
       while(j < words.length && len+ (j-i) + words[j].length() <= L) len += words[j++].length();  
       // # of space need to be inserted between each word is j==i?0:(L-len)/(j-i)  
       int space = j<=i+1?0:(L-len)/(j-i-1);  
       // # of space remained, L - len - space*(j-i);  
       int remain = L -len- space*(j-i-1);  
       // construct a line  
       StringBuilder s = new StringBuilder();  
       // one word case & last line case  
       if(j==words.length || j<=i+1){  
         for(int t = i;t < j;t++){  
           s.append(words[t]);  
           if(t!=j-1) s.append(" ");  
         }  
         remain += space*(j-i-1)-(j-i-1);  
         for(int t = 0;t < remain;t++) s.append(" ");  
       }else{  
         // general case  
         for(int t = i;t < j;t++,remain--){  
           s.append(words[t]);  
           if(t!=j-1) for(int u = 0;u < space;u++) s.append(" ");  
           if(remain > 0) s.append(" ");  
         }  
       }  
       // add line  
       list.add(s.toString());  
       i = j;  
     }  
     return list;  
   }  
 }  

No comments:

Post a Comment