LeetCode 68. Text Justification题目解析-wowAC

Description

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.

题目复述

给定一个word数组和一个长度L,格式化字符串数组,使得每行恰好有L个字符串,每行应该安排尽可能多的单词,使用' '填充,靠左边的' '应该多于右边的空格数,最后一行比较特殊,单词之间仅有一个空格,末尾用' '填充。

题目解析

直接按照题目的意思做,在实现的时候i, j表示每行安排的单词的区间,单词之间的空格数尽可能平分,有多余的先给左边的空格。使用base和extra控制空格,base为单词之间基础空格数,如果此时extra大于0,那么表示还需要在加一个空格。

注意每行只能安排一个单词的情况。

class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        int i = 0, j = -1, width = 0;
        vector<string> res;

        while(1) {
            //计算每行可以安排的单词的区间 [i, j]
            while(j+1<words.size()) {
                 if(width+words[j+1].length()+j+1-i <= maxWidth) {
                     width += words[j+1].length();
                     j++;
                 }else
                    break;
            }
            
            if(i > j) break;   //可以安排0个单词,即所有单词安排完毕

            string line = "";
            if(j == words.size()-1) {  //最后一行
                for(int k=i; k<=j; k++) {
                    line += words[k];
                    if(k == j) continue;
                    line += ' ';
                }
            }else { //非最后一行
                int space = maxWidth - width, base, extra;
                if(i != j) {  //行内单词数大于1
                    base = space / (j-i);
                    extra = space % (j-i);
                }
                for(int k=i; k<=j; k++) {
                    line += words[k];
                    if(k==j) continue;
                    line += string(base, ' ');
                    if(extra> 0) {
                        line += " ";
                        extra--;
                    }
                }

            }
            line += string(maxWidth - line.length(), ' ');
            //cout<<line<<" "<<line.length()<<endl;
            res.push_back(line);
            i = j+1; j = i-1;
            width = 0;
        }
        return res;
    }
};

发表评论

电子邮件地址不会被公开。 必填项已用*标注