Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 68. Text Justification #68

Open
grandyang opened this issue May 30, 2019 · 1 comment
Open

[LeetCode] 68. Text Justification #68

grandyang opened this issue May 30, 2019 · 1 comment

Comments

@grandyang
Copy link
Owner

grandyang commented May 30, 2019


请点击下方图片观看讲解视频
Click below image to watch YouTube Video
Video

Given an array of strings 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 does 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.  "
]

Example 2:

Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
Output:
[
  "What   must   be",
  "acknowledgment  ",
  "shall be        "
]
Explanation: Note that the last line is "shall be    " instead of "shall     be", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.

Example 3:

Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20
Output:
[
  "Science  is  what we",
  "understand      well",
  "enough to explain to",
  "a  computer.  Art is",
  "everything  else  we",
  "do                  "
] 

Constraints:

  • 1 <= words.length <= 300
  • 1 <= words[i].length <= 20
  • words[i] consists of only English letters and symbols.
  • 1 <= maxWidth <= 100
  • words[i].length <= maxWidth

这道文本左右对齐的题像极了 word 软件里面的文本左右对齐功能,这道题博主前前后后折腾了快四个小时终于通过了OJ,完成了之后想着去网上搜搜看有没有更简单的方法,搜了一圈发现都差不多,都挺复杂的,于是乎就按自己的思路来说吧,由于返回的结果是多行的,所以在处理的时候也要一行一行的来处理,首先要做的就是确定每一行能放下的单词数,这个不难,就是比较k个单词的长度和加上 k-1 个空格的长度跟给定的长度 maxWidth 来比较即可,找到了一行能放下的单词个数,然后计算出这一行存在的空格的个数,是用给定的长度 maxWidth 减去这一行所有单词的长度和。

得到了空格的个数之后,就要在每个单词后面插入这些空格,这里有两种情况,比如某一行有两个单词 "to" 和 "a",给定长度 maxWidth 为6,如果这行不是最后一行,那么应该输出 "to a",如果是最后一行,则应该输出 "to a ",所以这里需要分情况讨论,最后一行的处理方法和其他行之间略有不同。最后一个难点就是,如果一行有三个单词,这时候中间有两个空,如果空格数不是2的倍数,那么左边的空间里要比右边的空间里多加入一个空格,那么这里只需要用总的空格数除以空间个数,能除尽最好,说明能平均分配,除不尽的话就多加个空格放在左边的空间里,以此类推,具体实现过程还是看代码吧:

class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        vector<string> res;
        int i = 0, n = words.size();
        while (i < n) {
            int j = i, len = 0;
            while (j < n && len + words[j].size() + j - i <= maxWidth) {
                len += words[j++].size();
            }
            string cur;
            int space = maxWidth - len;
            for (int k = i; k < j; ++k) {
                cur += words[k];
                if (space > 0) {
                    int cnt;
                    if (j == n) { 
                        if (j - k == 1) cnt = space;
                        else cnt = 1;
                    } else {
                        if (j - k > 1) {
                            if (space % (j - k - 1) == 0) cnt = space / (j - k - 1);
                            else cnt = space / (j - k - 1) + 1;
                        } else cnt = space;
                    }
                    cur.append(cnt, ' ');
                    space -= cnt;
                }
            }
            res.push_back(cur);
            i = j;
        }
        return res;
    }
};

Github 同步地址:

#68

类似题目:

Rearrange Spaces Between Words

Divide a String Into Groups of Size k

Split Message Based on Limit

参考资料:

https://leetcode.com/problems/text-justification/

https://leetcode.com/problems/text-justification/solutions/24873/share-my-concise-c-solution-less-than-20-lines/

https://leetcode.com/problems/text-justification/solutions/24902/java-easy-to-understand-broken-into-several-functions/

LeetCode All in One 题目讲解汇总(持续更新中...)

(欢迎加入博主的知识星球,博主将及时答疑解惑,并分享刷题经验与总结,快快加入吧~)

知识星球 喜欢请点赞,疼爱请打赏❤️~.~

微信打赏

|

Venmo 打赏


---|---

@jimbinc
Copy link

jimbinc commented Jul 29, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants