Leetcode P0068"Text Justification" 题解

2020/08/28 Leetcode

博文中会简要介绍Leetcode P0068题目分析及解题思路。

“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.  "
    ]
    

需要考虑许多corner cases,所以要求解题的人有足够耐心并且有一定的debug技巧和能力。

以下是Java的题解代码实现。

class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {
        List<String> text = new ArrayList<>();
        if (words == null || words.length == 0)
            return text;
        
        int lineLen = words[0].length(), left = 0;
        for (int idx=1; idx<words.length; ++idx) {
            // 判断当前行未用长度是否可以继续填充
            if (lineLen+words[idx].length()+1 > maxWidth) {
                String line = this.justify(words, left, idx, lineLen, maxWidth);
                text.add(line);
                lineLen = words[idx].length();
                left = idx;
            }
            else {
                lineLen += words[idx].length()+1;
            }
            
        }
        
        text.add(this.justify(words, left, words.length, -1, maxWidth));
        return text;
    }
    
    private String justify(String[] words, int start, int end, int len, int maxWidth) {
        StringBuilder line = new StringBuilder();
        // 不是最后一行
        if (len != -1) {
            int numOfRemainedSpaces = maxWidth-len;
            int numOfIntervals = end-start-1;
            int[] spacesInInterval = new int[numOfIntervals];
            
             // 如果只有一个单词
            if (numOfIntervals == 0) {
                line.append(words[end-1]);
                for (int itr=0; itr<numOfRemainedSpaces; ++itr)
                    line.append(' '); 
            }
            else {
                // 计算每个间隔的空格个数
                int numOfExtraSpaces = numOfRemainedSpaces%numOfIntervals;
                for (int idx=0; idx<numOfIntervals; ++idx) {
                    spacesInInterval[idx] = numOfRemainedSpaces/numOfIntervals+1;
                    // 额外的空格平均地添加到从左往右的每个间隔中
                    if (numOfExtraSpaces > 0) {
                        ++spacesInInterval[idx];
                        --numOfExtraSpaces;
                    }
                }

                for (int idx=0; idx<numOfIntervals; ++idx) {
                    line.append(words[start+idx]);
                    for (int itr=0; itr<spacesInInterval[idx]; ++itr)
                        line.append(' ');
                }
                line.append(words[end-1]);
            }
        }
        else {
            line.append(words[start]);
            for (int itr=start+1; itr<end; ++itr) {
                line.append(' ');
                line.append(words[itr]);
            }
            
            int numOfRemainedSpaces = maxWidth-line.length();
            for (int itr=0; itr<numOfRemainedSpaces; ++itr) {
                line.append(' ');
            }
               
        }
        
        return line.toString();
    }
}

以下是C++的题解代码实现。

class Solution {
private:
    string justified(vector<string>::const_iterator b, vector<string>::const_iterator e, int len, int count) {
		// special case
        if (b == e) {
            string ans = *b;
            ans.append(len - count, ' ');
            return ans;
        }
        
        int spaces = len - count;
        int d = spaces % (e - b), c = spaces / (e - b);
        string ans;
        
        for(auto p = b; p < e; p++) {
            ans.append(*p);
            if (p - b < d) {
                ans.append(c + 1, ' ');
            } else {
                ans.append(c, ' ');
            }
        } 
        ans.append(*e);
        return ans;
    }

public:
    vector<string> fullJustify(const vector<string>& words, int maxWidth) {
        vector<string> ans;
        // init
        auto beg = words.begin();
        int count = beg->size();

        // loop
        for(auto i = words.begin() + 1; i != words.end(); i++) {
            count += i->size();
            if (count + (i - beg) > maxWidth) {
                ans.push_back(justified(beg, i-1, maxWidth, count - i->size()));
                beg = i;
                count = i->size();
            }
        }

        // in the end merge all and append spaces
        string tmp(*beg);
        for(auto i = beg + 1; i < words.end(); i++) 
            tmp.append(" " + *i);
        tmp.append(maxWidth - tmp.length(), ' ');
        ans.push_back(tmp);
        
        return ans;
    }
};

Search

    Table of Contents