LeetCode 68 - 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.  "
]
  • 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.
public ArrayList<String> fullJustify(String[] words, int L) {
        ArrayList<String> result = new ArrayList<String>();
        if (words == null || words.length == 0)
            return result;
        int begin = 0, end = 0;     // words[begin...end-1] as a line
        while (begin < words.length) {
            // Determine end such that words[begin...end-1] fit in a line and
            // words[begin...end] do not.
            int currentLength = words[begin].length();
            for (end = begin+1; end < words.length; end++) {
                if (currentLength + words[end].length() + 1 <= L)
                    currentLength += words[end].length() + 1;
                else
                    break;
            }
            // Construct a justified line with words[begin...end-1]
            StringBuilder temp = new StringBuilder();
            temp.append(words[begin]);
            if (end == words.length || end == begin+1) {    // Last line or a line with only one word
                // Left justified
                for (int i = begin+1; i < end; i++) {
                    temp.append(' ');
                    temp.append(words[i]);
                }
                for (int i = 0; i < L - currentLength; i++)
                    temp.append(' ');
            } else {        // Regular lines
                // Fully justified
                int spaceInBetween = end - begin - 1;
                double spaces = L - currentLength + spaceInBetween;
                for (int i = begin+1; i < end; i++) {
                    for (int j = 0; j < spaces/spaceInBetween; j++) {
                        temp.append(' ');
                    }
                    spaces -= Math.ceil(spaces/spaceInBetween);
                    spaceInBetween--;
                    temp.append(words[i]);
                }
            }
            // Add the line to the resulting list, and slide the window to the next position
            result.add(temp.toString());
            begin = end;
        }
        return result;
    }
https://discuss.leetcode.com/topic/9147/simple-java-solution
    public List<String> fullJustify(String[] words, int L) {
        List<String> lines = new ArrayList<String>();
        
        int index = 0;
        while (index < words.length) {
            int count = words[index].length();
            int last = index + 1;
            while (last < words.length) {
                if (words[last].length() + count + 1 > L) break;
                count += words[last].length() + 1;
                last++;
            }
            
            StringBuilder builder = new StringBuilder();
            int diff = last - index - 1;
            // if last line or number of words in the line is 1, left-justified
            if (last == words.length || diff == 0) {
                for (int i = index; i < last; i++) {
                    builder.append(words[i] + " ");
                }
                builder.deleteCharAt(builder.length() - 1);
                for (int i = builder.length(); i < L; i++) {
                    builder.append(" ");
                }
            } else {
                // middle justified
                int spaces = (L - count) / diff;
                int r = (L - count) % diff;
                for (int i = index; i < last; i++) {
                    builder.append(words[i]);
                    if (i < last - 1) {
                        for (int j = 0; j <= (spaces + ((i - index) < r ? 1 : 0)); j++) {
                            builder.append(" ");
                        }
                    }
                }
            }
            lines.add(builder.toString());
            index = last;
        }
        
        
        return lines;
    }
http://yuanhsh.iteye.com/blog/2191422
  1. public List<String> fullJustify(String[] words, int L) {  
  2.     List<String> res = new ArrayList<>();  
  3.     int n = words.length;  
  4.     char[] spaces = new char[L];  
  5.     Arrays.fill(spaces, ' ');  
  6.     for(int i=0; i<n; i++) {  
  7.         int len = words[i].length();  
  8.         int j = i;  
  9.         while(i<n-1 && len+1+words[i+1].length()<=L) {  
  10.             len += 1+words[++i].length();  
  11.         }  
  12.         StringBuilder sb = new StringBuilder(words[j]);  
  13.         if(j == i || i==n-1) {  
  14.             while(i==n-1 && j < i) {  
  15.                 sb.append(" "+words[++j]);  
  16.             }  
  17.             sb.append(spaces, 0, L-sb.length());  
  18.         } else {  
  19.             int avg = (L-len)/(i-j);  
  20.             int rem = (L-len)%(i-j);  
  21.             while(j < i) {  
  22.                 sb.append(spaces, 0, avg+1);  
  23.                 if(rem-- > 0) sb.append(" ");  
  24.                 sb.append(words[++j]);  
  25.             }  
  26.         }  
  27.         res.add(sb.toString());  
  28.     }  
  29.     return res;  
  30. }  

  1. public List<String> fullJustify(String[] words, int L) {  
  2.     List<String> list = new ArrayList<>();  
  3.     int n = words.length;  
  4.     char[] spaces = new char[L];  
  5.     Arrays.fill(spaces, ' ');  
  6.     for(int i=0; i<n; i++) {  
  7.         int j = i;   
  8.         int len = words[i].length();  
  9.         while(i<n-1 && len+1+words[i+1].length()<=L) {  
  10.             len += 1+words[++i].length();  
  11.         }  
  12.         //只有一个word或者是最后一行的时候,需要左对齐  
  13.         boolean left = (j==i || i==n-1);  
  14.         int avg = left ? 0 : (L-len) / (i-j); //平均空格个数-1  
  15.         int rem = left ? 0 : (L-len) % (i-j); //平均之后多出来的空格个数  
  16.         StringBuilder sb = new StringBuilder(words[j]);  
  17.         while(j < i) {  
  18.             sb.append(spaces, 0, avg+1);  
  19.             if(rem-- > 0) sb.append(' ');  
  20.             sb.append(words[++j]);  
  21.         }  
  22.         sb.append(spaces, 0, L-sb.length());  
  23.         list.add(sb.toString());  
  24.     }  
  25.     return list;  
  26. }
https://discuss.leetcode.com/topic/4189/share-my-concise-c-solution-less-than-20-lines/3
For each line, I first figure out which words can fit in. According to the code, these words are words[i] through words[i+k-1]. Then spaces are added between the words. The trick here is to use mod operation to manage the spaces that can't be evenly distrubuted: the first (L-l) % (k-1) gaps acquire an additional space.
    public List<String> fullJustify(String[] words, int L) {
        List<String> list = new LinkedList<String>();
        
        for (int i = 0, w; i < words.length; i = w) {
            int len = -1;
            for (w = i; w < words.length && len + words[w].length() + 1 <= L; w++) {
                len += words[w].length() + 1;
            }
            
            StringBuilder strBuilder = new StringBuilder(words[i]);
            int space = 1, extra = 0;
            if (w != i + 1 && w != words.length) { // not 1 char, not last line
                space = (L - len) / (w - i - 1) + 1;
                extra = (L - len) % (w - i - 1);
            }
            for (int j = i + 1; j < w; j++) {
                for (int s = space; s > 0; s--) strBuilder.append(' ');
                if (extra-- > 0) strBuilder.append(' ');
                strBuilder.append(words[j]);
            }
            int strLen = L - strBuilder.length();
            while (strLen-- > 0) strBuilder.append(' ');
            list.add(strBuilder.toString());
        }
        
        return list;
    }
http://buttercola.blogspot.com/2015/10/leetcode-text-justification.html
    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());
        }
    }


    vector<string> fullJustify(vector<string> &words, int L) {
        int start = 0, end = -1, totLen = 0;
        bool isLast = false;
        vector<string> ret;
        int i=0;
        while(i<words.size()) {
            if(words[i].size()>L) return ret;
            int newLen = totLen + (end-start+1) + words[i].size();
            if(newLen<=L) { // words[i] can be in current line
                end  = i;
                totLen += words[i].size();
                i++;
            }
            else {  // word[i-1] is the end of a line
                string line = createLine(words, L, start, end, totLen, false);
                ret.push_back(line);
                start = i;
                end = i-1;
                totLen = 0;
            }
        }
        
        string lastLine = createLine(words, L, start, end, totLen, true);
        ret.push_back(lastLine);
        return ret;
    }
    
http://bangbingsyb.blogspot.com/2014/11/leetcode-text-justification.html
比较麻烦的字符串细节实现题。需要解决以下几个问题:
1. 首先要能判断多少个word组成一行:
这里统计读入的所有words的总长curLen,并需要计算空格的长度。假如已经读入words[0:i]。当curLen + i <=L 且加curLen + 1 + word[i+1].size() > L时,一行结束。
2. 知道一行的所有n个words,以及总长curLen之后要决定空格分配:
平均空格数:k = (L - curLen) / (n-1)
前m组每组有空格数k+1:m = (L - curLen) % (n-1)
例子:L = 21,curLen = 14,n = 4
k = (21 - 14) / (4-1) = 2
m = (21 - 14) % (4-1)  = 1
A---B--C--D
3. 特殊情况:
(a) 最后一行:当读入到第i = words.size()-1 个word时为最后一行。该行k = 1,m = 0
(b) 一行只有一个word:此时n-1 = 0,计算(L - curLen)/(n-1)会出错。该行k = L-curLen, m = 0
(c) 当word[i].size() == L时。
   string createLine(vector<string> &words, int L, int start, int end, int totLen, bool isLast) {
        string ret;
        if(start<0 || end>=words.size() || start>end) return ret;
        ret.append(words[start]);
        int n = end-start+1;
        
        // special case: one word or last line - left justified
        if(n==1 || isLast) {
            for(int i=start+1; i<=end; i++) 
                ret.append(" " + words[i]);
            int j = L-totLen-(n-1);
            ret.append(j, ' ');
            return ret;
        }
        
        // normal case: fully justified
        int k = (L-totLen)/(n-1), m = (L-totLen)%(n-1);
        for(int i=start+1; i<=end; i++) {
            int nspace = i-start<=m ? k+1 : k;
            ret.append(nspace,' ');
            ret.append(words[i]);
        }
        return ret;
    }
https://github.com/writecoffee/algorithms/blob/master/algo4/greedy/gd_text_justification.java
    public ArrayList<String> fullJustify(String[] words, int L) {
        ArrayList<String> result = new ArrayList<String>();
        int i = 0, m = words.length;

        while (i < m) {
            int n = words[i].length(), next = i + 1;

            while (next < m && n + words[next].length() + (next - i) <= L) {
                n += words[next++].length();
            }

            StringBuilder sb = new StringBuilder();
            sb.append(words[i]);

            boolean isLastLine = (next == m);
            boolean oneWord = (next == i + 1);

            int average = isLastLine || oneWord ? 1 : (L - n) / (next - i - 1);
            int extra = isLastLine || oneWord ? 0 : (L - n) % (next - i - 1);

            for (int j = i + 1; j < next; ++j, --extra) {
                sb.append(fillChar(extra > 0 ? average + 1 : average, ' '));
                sb.append(words[j]);
            }

            result.add(sb.append(fillChar(L - sb.length(), ' ')).toString());
            i = next;
        }

        return result;
    }

    private String fillChar(int count, char c) {
        char[] array = new char[count];
        Arrays.fill(array, c);
        return new String(array);
    }
Left Justify Text from EPI
  public static List<String> leftJustifiedText(List<String> words, int L) {
    int lastIdx = 0, numWords = 0, len = 0;
    List<String> res = new ArrayList<String>();
    for (int i = 0; i < words.size(); ++i) {
      ++numWords;
      int lineLen = len + words.get(i).length()
          + (numWords >= 2 ? numWords - 1 : 0);
      if (lineLen == L) {
        res.add(joinALineWithSpace(words, lastIdx, i, i - lastIdx));
        lastIdx = i + 1;
        numWords = 0;
        len = 0;
      } else if (lineLen > L) {
        res.add(joinALineWithSpace(words, lastIdx, i - 1, L - len));
        lastIdx = i;
        numWords = 1;
        len = words.get(i).length();
      } else { // lineLen < L.
        len += words.get(i).length();
      }
    }

    // Handles the last line.
    if (numWords != 0) {
      res.add(joinALineWithSpace(words, lastIdx, words.size() - 1, L - len));
    }
    return res;
  }

  // Joins strings in words[start : end].
  private static String joinALineWithSpace(List<String> words, int start,
      int end, int numSpaces) {
    int numWords = end - start + 1;
    StringBuilder line = new StringBuilder();
    for (int i = start; i < end; ++i) {
      line.append(words.get(i));
      int numCurrSpace = (int) Math.ceil((double) numSpaces / numWords - 1);
      for (int j = 0; j < numCurrSpace; j++) {
        line.append(' ');
      }
      numSpaces -= numCurrSpace;
      --numWords;
    }
    line.append(words.get(end));
    for (int j = 0; j < numSpaces; j++) {
      line.append(' ');
    }
    return line.toString();
  }
Read full article from LeetCode - Text Justification | Darren's Blog

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts