LeetCode-68.Text Justification

来源:互联网 发布:剑三和尚正太捏脸数据 编辑:程序博客网 时间:2024/06/03 16:11

https://leetcode.com/problems/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."]
L16.

Return the formatted lines as:

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

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

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.

思路比较简单,没用什么特别技巧。

首先把所有单词拼接成一个字符串,用空格隔开每个单词

再依次读取每一行并进行处理

class Solution {public:    string insert(const string &s, int len)    {    string res = "";    int count = 0, left = len - s.length();    for (char c : s)    count += (c == ' ' ? 1 : 0);    if (count == 0)    return insertLast(s,len);    int per = left / count, assignedN = left%count;    string insertStr = "";    for (int i = 0; i < per; ++i)    insertStr += " ";    for (char c : s)    {    res += c;    if (c == ' ')    {    res += insertStr;    if (assignedN-- > 0)    res += " ";    }    }    return res;    }        string insertLast(const string &s, int len)    {    string insertStr = "";    int ll = len - s.length();    for (int i = 0; i < ll; ++i)    insertStr += " ";    return s + insertStr;    }        vector<string> fullJustify(vector<string>& words, int maxWidth)    {    vector<string> res;    int n = words.size();    if (n == 0)    return res;        string s = "";    for (int i = 0; i < n - 1; i++)    s += words[i] + " ";    s += words[n - 1];    int len = s.length(), offset = 0, lastOffset = 0;    if (len <= maxWidth)    {    res.push_back(insertLast(s, maxWidth));    return res;    }    while (offset < len)    {    offset += maxWidth;    if (offset >= len)    {    res.push_back(insertLast(s.substr(lastOffset), maxWidth));    break;    }        while (s[offset] != ' ')    offset--;        string part = s.substr(lastOffset, offset - lastOffset);    res.push_back(insert(part, maxWidth));        offset++;    lastOffset = offset;    }    return res;    }};



0 0
原创粉丝点击