• [LeetCode 68] Text Justification


    Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth 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 maxWidth 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.

    Note:

    • A word is defined as a character sequence consisting of non-space characters only.
    • Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
    • The input array words contains at least one word.

    Example 1:

    Input:
    words = ["This", "is", "an", "example", "of", "text", "justification."]
    maxWidth = 16
    Output:
    [
       "This    is    an",
       "example  of text",
       "justification.  "
    ]
    

    Example 2:

    Input:
    words = ["What","must","be","acknowledgment","shall","be"]
    maxWidth = 16
    Output:
    [
      "What   must   be",
      "acknowledgment  ",
      "shall be        "
    ]
    Explanation: Note that the last line is "shall be    " instead of "shall     be",
                 because the last line must be left-justified instead of fully-justified.
                 Note that the second line is also left-justified becase it contains only one word.
    

    Example 3:

    Input:
    words = ["Science","is","what","we","understand","well","enough","to","explain",
             "to","a","computer.","Art","is","everything","else","we","do"]
    maxWidth = 20
    Output:
    [
      "Science  is  what we",
      "understand      well",
      "enough to explain to",
      "a  computer.  Art is",
      "everything  else  we",
      "do                  "
    ]


    This problem is fairly straightforward. The solution is "do what is asked". i.e, starting from a word, greedily add more words to one line. Then format this line as required. The general formatting
    requirement can be generalized as follows.
    1. If it is the last line, then there is only 1 space in between words, all the remaining spaces go at the end.
    2. If not the last line and there are at most 2 words, add all spaces in between these 2 words, treating the 1 word case having an imaginary empty word as the 2nd word.
    3. If not the last lien and there are at least 3 words, if we can evenly distribute all spaces in between all words, do it; otherwise, assign 1 extra space in between the first totalSpace % wordCnt words.

    To speed up the greedy line grouping, we should first compute a prefix sum of all words' length; Then use binary search when searching the max number of words that can be grouped into the next line.

    class Solution {
        public List<String> fullJustify(String[] words, int maxWidth) {
            List<String> ans = new ArrayList<>();
            int n = words.length;
            int[] ps = new int[n];
            ps[0] = words[0].length();
            for(int i = 1; i < n; i++) {
                ps[i] = ps [i - 1] + words[i].length();
            }
            
            int j = 0;
            while(j < n) {
                int k = binarySearch(ps, j, maxWidth);
                int totalSpaces = maxWidth - (ps[k] - (j > 0 ? ps[j - 1] : 0));
                int wordCnt = k - j + 1;
                StringBuilder buffer = new StringBuilder();
                //last line
                if(k == n - 1) {
                    addWordsWithSpace(buffer, words, j, k, 1);
                    addNSpaces(buffer, totalSpaces - (k - j));
                }
                else if(wordCnt <= 2) {
                    buffer.append(words[j]);
                    addNSpaces(buffer, totalSpaces);
                    if(k > j) {
                        buffer.append(words[k]);
                    }
                }
                else {
                    int spaceCnt = totalSpaces / (wordCnt - 1);
                    int extra = totalSpaces % (wordCnt - 1);
                    addWordsWithSpace(buffer, words, j, j + extra, spaceCnt + 1);
                    addNSpaces(buffer, spaceCnt);
                    addWordsWithSpace(buffer, words, j + extra + 1, k, spaceCnt);
                }
                ans.add(buffer.toString());
                j = k + 1;
            }
            return ans;
        }
        
        private void addWordsWithSpace(StringBuilder buffer, String[] words, int l, int r, int spaceCnt) {
            for(int i = l; i <= r; i++) {
                buffer.append(words[i]);
                if(i < r) {
                    addNSpaces(buffer, spaceCnt);
                }            
            }
        }
        
        private void addNSpaces(StringBuilder buffer, int N) {
            for(int t = 0; t < N; t++) {
                buffer.append(" ");
            }        
        }
        
        private int binarySearch(int[] ps, int startIdx, int target) {
            int l = startIdx, r = ps.length - 1;
            while(l < r - 1) {
                int mid = l + (r - l) / 2;
                if(ps[mid] - (startIdx > 0 ? ps[startIdx - 1] : 0) + mid - startIdx > target) {
                    r = mid - 1;
                }
                else {
                    l = mid;
                }
            }
            if(ps[r] - (startIdx > 0 ? ps[startIdx - 1] : 0) + r - startIdx <= target) {
                return r;
            }
            return l;
        }
    }
    
    
    

    This problem is similar with the following related problem that requires dynamic programming to solve. Because this problem asks to solve it greedily, so it is an implementation-focused problem.

    Related Problems

    [Coding Made Simple] Text Justification

     
  • 相关阅读:
    java--Compara比较字符串排序(引用类型都可以)
    java---递归遍历文件
    java 增强for循坏遍历set 集合嵌套
    java-手写实现map
    ajax请求拿到多条数据拼接显示在页面中
    ajax取到数据后如何拿到data.data中的属性值
    .NET CORE IIS 500.21
    ConfigurationErrorsException: Unrecognized configuration section system.data.
    关于ajax中return并不能作为方法的返回值
    .net core 的跨域
  • 原文地址:https://www.cnblogs.com/lz87/p/10223077.html
Copyright © 2020-2023  润新知