【LeetCode】68. Text Justification

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 exactlyL 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.

 

贪心算法,主要这几步骤:

使用字符串line记录当前行

1、计算能否加入下一个单词word

2、若长度L能容纳,则加入line,并更新line长度

3、若长度L不能容纳,则line即为符合条件的一行,并重新调整单词间隔,构成newline

4、单词全部添加完毕,在newline尾部加入空格。

注意:添加最后一行

class Solution {
public:
    vector<string> fullJustify(vector<string> &words, int L) {
        vector<string> ret;
        if(words.empty())
            return ret;
        string line = words[0];
        int len = words[0].size();
        int begin = 0;
        int end = 0;
        for(int i = 1; i < words.size(); i ++)
        {
            len = len + 1 + words[i].size();
            if(len <= L)
            {//can insert words[i]
                line = line + " " + words[i];
            }
            else
            {
                len = len - 1 - words[i].size();
                end = i-1;
                int extraspaces = L - len;
                string newline;
                for(int j = begin; j < end; j ++)
                {
                    string slot(ceil((double)extraspaces/(end-j)), ' ');
                    newline = newline + words[j] + " " + slot;
                    extraspaces -= slot.size();
                }
                newline += words[end];
                string extraStr(L-newline.size(), ' ');
                ret.push_back(newline+extraStr);
                line = words[i];
                len = words[i].size();
                begin = i;
            }
        }
        string extraStr(L-line.size(), ' ');
        ret.push_back(line+extraStr);
        
        return ret;
    }
};

posted @ 2014-12-09 21:24  陆草纯  阅读(403)  评论(0编辑  收藏  举报