Text Justification

来源:互联网 发布:宝岛台湾知多少 编辑:程序博客网 时间:2024/06/13 20:49

题目:leetcode

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


vector<string> fullJustify(vector<string> &words, int L) {vector<string> res;if (words.empty() || L < 0)return res;if(L==0){    bool feikong=true;    for(auto &i:words)    {        if(!i.empty())        {feikong=false;        break;}    }    if(feikong)    {        vector<string> r(words.size(),"");        return r;    }    else    return res;}int start = 0, end = 0, cursum = 0;for (int i = 0; i<words.size(); i++){cursum += words[i].size();if (cursum >= L - 1){//处理[start,end)内的单词if (cursum <= L){end = i + 1;}else{end = i;}if(end==words.size())//最后一行,左对齐{    string tmp;for(int i=start;i<end;i++){    tmp+=words[i]+" ";}tmp.erase(tmp.end()-1);int size=tmp.size();int offset=L-size;if(offset>0){    string space(offset,' ');    tmp+=space;}res.push_back(tmp);return res;}else if (end == start)//单个单词的长度超过L{res.push_back(words[start]);cout << words[start] << endl;start++;// cursum=0;//continue;}else if (end == start + 1)//单个单词,左对齐{string tmp = words[start];string space(L - tmp.size(), ' ');tmp += space;res.push_back(tmp);start = end;}else//多个单词{if (cursum>L){cursum = cursum - 1 - words[i].size();//不要第i个单词和最后一个空格}int diff = L - cursum;//多出来的空间,要用空格填满int words_num = end - start;int space_num = 1 + diff / (words_num - 1);vector<string> spaces(words_num - 1, string(space_num, ' '));//分配剩下的空格if (diff % (words_num - 1) != 0){int offset = diff % (words_num - 1);int index = 0;while (offset>0){spaces[index] += " ";offset--;index++;}}spaces.push_back("");//最后压入一个空字符串string tmp;for (int j = start, k = 0; j<end; j++, k++){tmp += words[j] + spaces[k];}res.push_back(tmp);start = end;}cursum = 0;i = start - 1;}elsecursum++;//加上一个空格}if (cursum != 0)//左对齐{end = words.size();string tmp;for(int i=start;i<end;i++){    tmp+=words[i]+" ";}tmp.erase(tmp.end()-1);int size=tmp.size();int offset=L-size;if(offset>0){    string space(offset,' ');    tmp+=space;}res.push_back(tmp);}return res;}


0 0
原创粉丝点击