Leetcode: Text Justification

来源:互联网 发布:网络博客娱乐平台出租 编辑:程序博客网 时间:2024/06/05 17:13

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

Return the formatted lines as:

[   "This    is    an",   "example  of text",   "justification.  "]

Note: Each word is guaranteed not to exceed L in length.

题目很长,不难,就是需要注意细节。

class Solution {public:    vector<string> fullJustify(vector<string> &words, int L) {        int length = 0;        vector<string> tmp;        vector<string> result;        for (int i = 0; i < words.size(); ++i) {            int left_len = L - length;            if (left_len < 0 || left_len < words[i].size()) {                // reimburse the last space added                ++left_len;                string line;                if (tmp.size() == 1) {                    line = tmp[0];                    line.append(left_len, ' ');                }                else {                    // have added one space between words                    int avg = left_len / (tmp.size() - 1) + 1;                    int remainder = left_len % (tmp.size() - 1);                    for (int j = 0; j < tmp.size() - 1; ++j) {                        line += tmp[j];                        line.append(avg, ' ');                        if (remainder-- > 0) {                            line.append(1, ' ');                        }                    }                    line += tmp.back();                }                result.push_back(line);                tmp.clear();                length = 0;                // handle this word again                --i;            }            else {                tmp.push_back(words[i]);                length += words[i].size() + 1;            }        }                if (!tmp.empty()) {            string line;            for (int j = 0; j < tmp.size() - 1; ++j) {                line += tmp[j] + ' ';            }            line += tmp.back();            line.append(L - line.size(), ' ');            result.push_back(line);        }                return result;    }};

0 0
原创粉丝点击