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.

click to show corner cases.

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.
 这题主要是对单词进行按行排序.主要要考虑的情况有三种:
1.提示中提醒的,一行只有一个单词,则放置在左边,left-justified.
2.最后一行,即使有多个单词,也是放置在左边,left-justified,多个单词时,之间只有一个空格.
3.不是最后一行,但是间隔无法整除时,左边要比右边间隔大,但是要尽量均分,即只能相差一个.
代码如下:
class Solution(object):
    def fullJustify(self, words, maxWidth):
        """
        :type words: List[str]
        :type maxWidth: int
        :rtype: List[str]
        """
        #slice the words in a sequential way, don't understand the last line meaning 
        if not words:
            return []
        res = []
        n = len(words)
        start = 0
        while start < n:
            lengthSum = 0
            cnt = 0
            while start+cnt < n and  lengthSum + len(words[start+cnt]) + cnt <=  maxWidth: #frist test whether can add the word, then add the word in the line
                lengthSum += len(words[start+cnt])
                cnt += 1
            #make the line
            if cnt == 1:
                res.append(words[start]+(maxWidth-lengthSum)*" ")
            elif start + cnt == n:  #the last line, several words together, left justify
                cur = " ".join(words[start: start+cnt])
                if len(cur) < maxWidth:
                    cur+= " "*(maxWidth-len(cur))
                res.append(cur)
            else: #common line
                avg = (maxWidth - lengthSum)/(cnt-1)
                if (maxWidth - lengthSum)%(cnt-1) == 0:
                    res.append((" "*avg).join(words[start:start+cnt]))
                else:
                    n1 = maxWidth - lengthSum - avg*(cnt-1) + 1#number of left slots has more space
                    n2 = avg - (cnt-1)
                    cur =(" "*(avg+1)).join(words[start:start+n1])
                    cur += " "*avg
                    cur += (" "*avg).join(words[start+n1:start+cnt])
                    res.append(cur)
            start += cnt

        return res

 参考leetcode精简思路,找长度一样,主要是生成行的时候简单:

vector<string> fullJustify(vector<string> &words, int L) {
    vector<string> res;
    for(int i = 0, k, l; i < words.size(); i += k) {
        for(k = l = 0; i + k < words.size() and l + words[i+k].size() <= L - k; k++) {
            l += words[i+k].size();
        }
        string tmp = words[i];
        for(int j = 0; j < k - 1; j++) {
            if(i + k >= words.size()) tmp += " ";
            else tmp += string((L - l) / (k - 1) + (j < (L - l) % (k - 1)), ' ');
            tmp += words[i+j+1];
        }
        tmp += string(L - tmp.size(), ' ');
        res.push_back(tmp);
    }
    return res;
}

 

 

posted on 2016-09-11 21:58  Sheryl Wang  阅读(177)  评论(0编辑  收藏  举报

导航