leetcode #68 in cpp

原创 2016年05月31日 04:42:44

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

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.


Solution: 

Honestly I do not like this kind of question. Collecting words in into a row is easy. We could simply check if we can put a word in this row. If we could put this word, then we collect this word and reduce the length of available space by the length of this word + 1(length of one space). It is quite frustrating to pad spaces into the row.

There are 2 cases when we pad space:

1. The row is the last row: we do not pad extra space between words. Just append them with 1 space in between. When necessary we append extra spaces to this row to reach maximum length.

2. The row is not the last row. Then we have to calculate how long the space is for each word when we pad the space. It is simply the currently allowable space length / (current number of word +1)to add into the row. Say we have "this", "isn't", "a", "dog", and length is 16. 

we know that 'this' must be at the front and 'dog' must be at the end. Before we insert 'a in front of 'dog', there are 16 - len(this)-len(dog) = 16 - 7 = 9 allowable space length. We have 2 word to add, and thus the current average length of space we should append is 9/3 = 3 when we add 'a'. Thus we append 3 spaces to 'a', and insert "a _ _ _" in front of 'dog'. When we come to 'isn't', the number to add is 1 and current allowable space length is 5 and thus we append 6/2 = 3 spaces. 

Code:

class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        vector<string> res;
        if(maxWidth == 0) return words;
        return collect(words, 0, maxWidth,res);
    }
    vector<string> collect(vector<string>&words, int start_ind, int maxWidth, vector<string> &res){
        int cur_length=0;//length of current words in the row
        int end_ind = start_ind; //end_ind points to the ending word of this row
        int i = 0;
        //collect words for this row
        for(int i = start_ind; i < words.size() &&cur_length + words[i].length() <= maxWidth;i++){//check if we can put this word
            if(cur_length + words[i].length() + 1 > maxWidth){//if we can put this word but cannot put an extra space behind it, then this is the end of the setence
                end_ind = i;
                break;
            }else{//if we can put one extra space behind it, then this is potentially not the end of a sentence
                end_ind = i;
                cur_length += words[end_ind].length() + 1;//add the word's length and one extra space
            };
        }
        //after collecting the row, add stirngs in the row and pad spaces into the row 
        //we are going to add string beween start_ind and end_ind
        if(end_ind==words.size() - 1){//if it is the last row, we need to follow the 'left' order
            for(int j = start_ind+1; j <= end_ind; j++){//append next words with one space in between
                words[start_ind]+=" "+words[j];
            }
            if(words[start_ind].length() < maxWidth)//fill the rest with space to reach maxWidth
                words[start_ind]+=string(maxWidth -words[start_ind].length(), ' ' );
            
            res.push_back(words[start_ind]);//push the last row into res and return res
            return res;
        }else{//if this is not the last row
            if(end_ind == start_ind ){//if this string contains only one word, put this word at the front and pad space
                    words[start_ind] +=string(maxWidth - words[start_ind].length(),' ');//pad extra space at the end
            }else{//this row contains more than 1 word
                int space_len = maxWidth;
                for(int i = end_ind; i >= start_ind; i --)
                    space_len -= words[i].length();//length of spaces in this row 
                int temp_end = end_ind-1;
                int avglen;
                //first we calculate how many spaces we should append to current word. Then we add this word to the last word of this row. 
                while(temp_end>start_ind){
                    avglen = space_len / (temp_end - start_ind+1);//length of space we should append to current word
                    words[end_ind] = words[temp_end] + string(avglen,' ') + words[end_ind];//add this word to the front of the last word in this word
                    temp_end--;//go to next word
                    space_len -= avglen;
                }
                words[start_ind]+= string(space_len,' ')+words[end_ind];//add the first word
               
            
            }
        
            res.push_back(words[start_ind]);
        }
        return collect(words, end_ind + 1,maxWidth, res );//go to the next section
    }
        
    
    
};


Leetcode 68. Text Justification 文本调整 解题报告

1 解题思想这道题,其实我也想不通为什么要标记为Hard模式,题目的大意就是对一个字符串数组进行格式化调整,输出对应的句子。 要求有: 1、每一行的字符串长度不能超过一个固定长度maxWidth ...
  • MebiuW
  • MebiuW
  • 2016年05月10日 23:58
  • 2237

leetcode 68:Text Justification细致分析,java实现

Given an array of words and a length L, format the text such that each line has exactly L characters...
  • tingting256
  • tingting256
  • 2015年11月12日 20:49
  • 360

LeetCode 68. Text Justification(文本对齐)

原题网址:https://leetcode.com/problems/text-justification/ Given an array of words and a length L, for...
  • jmspan
  • jmspan
  • 2016年05月22日 00:05
  • 260

[leetcode] 68. Text Justification

Given an array of words and a length L, format the text such that each line has exactly L characters...
  • TstsUgeg
  • TstsUgeg
  • 2016年04月21日 16:11
  • 481

LeetCode 68

Text Justification     这个题的意思比较简单,但是情况很复杂,输入一些列单词,然后将这些单词按照规定的长度组合,参照例子大概就可以知道组合的规律,首先分析一下,然后再给出解题思路...
  • zr1076311296
  • zr1076311296
  • 2016年06月24日 21:04
  • 1521

[leetcode] 【分治法】 50. Pow(x, n)

Implement pow(x, n). 题意 实现幂函数。 题解 使用分治法求解。 分:将n分成n/2  直到n=0时,返回1; 治:对n为偶数,返回两数相乘的结果,奇数再乘多一个x...
  • u014654002
  • u014654002
  • 2016年06月21日 00:37
  • 385

LeetCode Solution(持续更新,java>c++)

Title Add Date AC Rates
  • disappearedgod
  • disappearedgod
  • 2014年04月13日 21:52
  • 8839

leetcode 68: Interleaving String

leetcode 68 Interleaving String
  • xudli
  • xudli
  • 2013年02月05日 08:29
  • 1067

LeetCode 68 -Text Justification

Text Justification Given an array of words and a length L, format the text such that each line has...
  • ywcpig
  • ywcpig
  • 2016年10月17日 21:10
  • 429

[leetcode 68] Text Justification

Given an array of words and a length L, format the text such that each line has exactly L characters...
  • xinxinxv
  • xinxinxv
  • 2015年01月14日 17:57
  • 177
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode #68 in cpp
举报原因:
原因补充:

(最多只允许输入30个字)