码迷,mamicode.com
首页 > 其他好文 > 详细

Text Justification -- leetcode

时间:2015-04-07 17:40:50      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:leetcode   面试   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.

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.



此代码在leetcode上实际运行时间为2ms。

基本思路为:

1, 按一个空格作为间隔的情况下,统计一行能装下的字数。

2, 不足L的话,平摊到每个间隔上。


下面代码中, spaces变量,表示,每个间隔的空格数

由于每个间隔的空格数,无法完全相等。

故用extra,表示将持有零头空格的间隔数。

末尾空格的补齐适用于最后一行。



class Solution {
public:
    vector<string> fullJustify(vector<string> &words, int L) {
        vector<string> ans;
        int begin = 0;
        while (begin < words.size()) {
            int last = begin;
            int linesize = words[begin++].size();
            while (begin < words.size() && linesize + 1 + words[begin].size() <= L) {
                linesize += 1 + words[begin].size();
                begin++;
            }
            
            int spaces = 1, extra = 0;
            if (begin < words.size() && begin != last + 1) {
                spaces = (L - linesize) / (begin - last - 1) + 1;
                extra = (L - linesize) % (begin - last - 1);
            }
            
            ans.push_back(words[last++]);
            while (extra--) {
                ans.back().append(spaces+1, ' ');
                ans.back().append(words[last++]);
            }
            while (last < begin) {
                ans.back().append(spaces, ' ');
                ans.back().append(words[last++]);
            }
            ans.back().append(L-ans.back().size(), ' ');
        }
        
        return ans;
    }
};


Text Justification -- leetcode

标签:leetcode   面试   justification   排版   

原文地址:http://blog.csdn.net/elton_xiao/article/details/44922205

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!