首页 > 编程语言 > 详细

(每日算法)leetcode--Text Justification(格式化字符串)

时间:2014-11-11 22:51:32      阅读:439      评论:0      收藏:0      [点我收藏+]

要求:

给定一组字符串,按照给定长度(eg.16)格式化显示,使每一行尽可能多的单词,单词之间的空格均衡-最左侧可以稍多,左右对齐。

最后一行靠左对齐,即最右侧可以没有间隙。

如下面的例子描述:

1)每一行16个字符

2)左右对齐,空格数均衡,最左侧的间隙可以多一个空格

3)单词不可以拆开,最后一行左对齐。

原题描述:

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.  "
]
代码如下:

vector<string> fullJustify(vector<string> &words, int L) {
     vector<string> result;
     const int n = words.size();
     int begin = 0, len = 0;//当前行的起点, 当前长度
     for(int i = 0; i < n; ++i)
     {
        if( len + words[i].size() + (i - begin) > L)
        {
            //如果加上第i个单词长度超过L,就作为一行添加到结果中
            //i-begin -- 指单词之间必须的一个空格数
            //先统计一行能容纳多少个单词,然后再真正的拼接
            //将words中begin到i-1的i-begin个单词拼接
            result.push_back(connect(words, begin, i-1, len, L, false));
            begin = i;
            len = 0;
        }
        len += words[i].size();//只是起统计这一行长度的作用
     }   
     //将最后一行单独处理
     result.push_back(connect(words, begin, n-1, len, L, true));
     return result;
    }
//参数说明
//begin-开始拼接的索引         end-结束拼接的索引
//len-字母的总个数            is_last-是否是最后一行
string connect(vector<string> &words, int begin, int end, 
                int len, int L, bool is_last)
{
    string s;
    int n = end - begin + 1;//要拼接的单词个数
    for(int i = 0; i < n; ++i)
    {
        s += words[begin + i];
        //添加一个新单词之后要添加空格
        addSpaces(s, i, n - 1, L - len, is_last);
    }
    //L--总共需要添加的空格数
    if(s.size() < L) 
        s.append(L - s.size(), ' ');
    return s;
}
//参数说明
//i-当前空隙的序号    n-空隙总数
//L-总共需要添加的空隙数
void addSpaces(string &s, int i, int n, int L, bool is_last)
{
    if(n < 1 || i > n - 1) return;
    int spaces = is_last ? 1 : (L/n + (i < (L % n) ? 1 : 0));
    s.append(spaces, ' ');
}


(每日算法)leetcode--Text Justification(格式化字符串)

原文:http://blog.csdn.net/yapian8/article/details/41018241

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!