Text Justification

来源:互联网 发布:git ssh 非22端口 编辑:程序博客网 时间:2024/05/20 04:30

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. ”
]
思路:假设每一行单词个数为num,纯单词长度为l,那么空格的长度为space=maxWidth-l,需要注意两点:(1)非最后一行,除了将space/(num-1)分给单词间隔之间外,还需要将extra=space%(num-1)个空格,依次分给前extra个单词间隔(每个单词间隔一个空格)
(2)最后一行,单词间隔为一个空格,剩下的空格放在最右端

class Solution {public:    string getNumSpace(int num){//返回num个空格        string space = "";        for(int i = 0; i < num; ++i)            space += " ";        return space;    }    string getLine(int start, int end, int space, vector<string> words){//单词的索引为start-end(包括end),space为剩余总空格数(包括两个单词之间的)        string ret = "";        int wordNum = end - start + 1;//计算单词个数        int splitSpace, leftSpace;        if(wordNum > 1){             splitSpace = space / (wordNum - 1);//单词之间的平均间隔            leftSpace = space % (wordNum - 1);}//计算剩余空格数         else{//只有一个单词            return words[start] + getNumSpace(space);        }        for(int i = start; i < end; ++i){            if(i - start < leftSpace)//剩余空格数分别加在前leftSpac个单词上                ret += words[i] + getNumSpace(splitSpace+1);            else                ret += words[i] + getNumSpace(splitSpace);        }        ret += words[end];        return ret;    }    vector<string> fullJustify(vector<string>& words, int maxWidth){        vector<string> ret;        int len = words.size(), i = 0;        int start = 0, lenCount = 0;        for(; i < len; ++i){            lenCount += words[i].length() + 1;//+1表示计算了空格的长度            if(lenCount - 1> maxWidth){                int leftSpace = maxWidth - lenCount + words[i].length() + 2 + (i-1-start);                 ret.push_back(getLine(start, i-1, leftSpace, words));                start = i;                lenCount = words[i].length() + 1;            }        }        //计算最后一行        string last = "";        for(i = start; i < len - 1; ++i){            last += words[i] + " ";        }        last += words[len - 1];        last += getNumSpace(maxWidth - last.length());        ret.push_back(last);        return ret;    }};
0 0
原创粉丝点击