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

分析

先确定能放入几个词
然后确定每个间隔处放几个空格以及前几个空格要多加空格
然后进行操作,要注意处理只能放一个词的情况以及最后一行的情况。

实现

class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        vector<string> ans;
        int start=0, i, length, n;
        while(start<words.size()){
            i=start+1; length=words[start].size(); n=1;
            while(i<words.size() && length+words[i].size()+1<=maxWidth){
                length += words[i].size() + 1;
                i++; n++;
            }
            string tmp(words[start]);
            int nb, nbb;
            if(n>1 && i<words.size()){
                nb = (maxWidth - length + n - 1) / (n - 1);
                nbb = (maxWidth - length + n - 1) % (n - 1);
                for(int j=start+1; j<i; j++){
                    for(int k=0; k<nb; k++)
                        tmp += ' ';
                    if(j-start<=nbb)
                        tmp += ' ';
                    tmp += words[j];
                }
            }
            else {
                for(int j=start+1; j<i; j++){
                    tmp += ' ';
                    tmp += words[j];
                }
                while(tmp.size()<maxWidth) tmp += ' ';
            }
            ans.push_back(tmp);
            start = i;
        }
        return ans;
    }
};

思考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,864评论 0 23
  • 油墨画卷,慢慢翻开。一幅江南烟雨夜,一个拱桥,一条小溪,一湖清水,一个孤影,一把琵琶加一搓香花。花开在梦里,幽幽清...
    wuwu35阅读 325评论 0 0
  • 连通、边界、可视化、看见 今天邀请小妹儿跟我结对,把团队的几个故障统计条件放到了度量系统上。以后每日立会前,防火墙...
    玉露君阅读 344评论 5 0
  • 我最开始并不知道我将来会这么喜欢英语,也不知道我可以轻松地拿到雅思听力满分。 小时候,不像是现在的小孩子从一年级开...
    吴端端阅读 434评论 0 0
  • 姓名:楼灵芝 单位:杭州熙林服饰 【日精进打卡第101天】 【知~学习】 《六项精进》背诵2遍,共488遍; 《大...
    心镜_8ef4阅读 129评论 0 0