题目:

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. "
]

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.

代码:

class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> ret;
vector<string> tmp; // words in one line
int width = ; // total width in one line
const char BLANK=' ';
int i=;
while ( i<words.size() )
{
// judge if a word can be added in a line
if ( width+words[i].size() <= maxWidth )
{
if ( width+words[i].size()==maxWidth )
{
tmp.push_back(words[i]);
width = maxWidth;
}
else
{
tmp.push_back(words[i]+string(,BLANK));
width += words[i].size()+;
}
}
// or create a new line & handle the words[i]
else
{
// CREAT A NEW LINE
// number of blank need to add
int blank_num = maxWidth - width;
if ( tmp.back()[tmp.back().size()-]==BLANK )
{
tmp.back() = string(tmp.back().begin(),tmp.back().end()-);
blank_num = blank_num + ;
}
// number of position for blanks
int pos_num = tmp.size()-;
if ( pos_num== )
{
ret.push_back(tmp.back()+string(blank_num, BLANK));
}
else
{
// number of blanks remain to be evenly distributed
int blank_remain = blank_num % pos_num;
for ( int j=; j<tmp.size()-; ++j )
{
tmp[j] = tmp[j]+ string(blank_num/pos_num, BLANK);
}
for ( int j=; j<blank_remain; ++j )
{
tmp[j] = tmp[j] + string(, BLANK);
}
string str = "";
for ( int j=; j<tmp.size(); ++j ) str += tmp[j];
ret.push_back(str);
}
// HANDLE THE words[i]
tmp.clear();
if ( words[i].size()==maxWidth )
{
tmp.push_back(words[i]);
width = maxWidth;
}
else
{
tmp.push_back(words[i]+string(, BLANK));
width = words[i].size()+;
}
}
++i;
}
// address the remain line
if ( tmp.size()!= )
{
int blank_num = maxWidth - width;
string last_line = "";
for ( int i=; i<tmp.size(); ++i ) last_line += tmp[i];
ret.push_back(last_line+string(blank_num, BLANK));
}
return ret;
}
};

tips:

1. 要对string的各种操作都很熟悉

2. 要理解对题意,重点是到底啥是evenly:意思是不能evenly,就从左边到右一个个分配。

3. 扫一扫各种test case,多扫几遍可以AC了。

这道题自己扫了4次,终于AC了;经验就是,如果不能做到第一次把所有关键细节都考虑完全了,至少把一些细节(诸如blank_num,pos_num,blank_remain)单独列拎出来,这样做的好处就是如果遇上各种需要考虑的corner cases可以单独处理这些关键细节,而不用影响其他的部分。

====================================================

第二次过这道题,算是写过的leetcode中最繁琐的之一了,欣慰的是一次AC了。

class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> ret;
vector<string> tmp;
int currWidth = ;
for ( int i=; i<words.size()-; ++i )
{
// no room for curr word
if ( currWidth+words[i].size()>maxWidth )
{
// address words already in tmp
int blank = maxWidth - currWidth + ;
tmp.back() = tmp.back().substr(,tmp.back().size()-);
if ( tmp.size()> ){
int even = blank/(tmp.size()-);
for ( int k=; k<tmp.size()-; k++ ) tmp[k] = tmp[k] + string(even,' ');
int remain = blank%(tmp.size()-);
for ( int k=; k<remain; k++ ) tmp[k] = tmp[k] + " ";
string str = "";
for ( int k=; k<tmp.size(); ++k ) str += tmp[k];
ret.push_back(str);
}
else{
tmp[] = tmp[]+string(blank,' ');
ret.push_back(tmp[]);
}
tmp.clear();
// consider words[i]'s width
if ( words[i].size()<maxWidth ) {
tmp.push_back(words[i]+" ");
currWidth = words[i].size()+;
}
else{
ret.push_back(words[i]);
currWidth = ;
}
}
// room for current word
else
{
// no room for extra blank
if ( currWidth+words[i].size()==maxWidth )
{
tmp.push_back(words[i]);
string str = "";
for ( int k=; k<tmp.size(); ++k ) str += tmp[k];
ret.push_back(str);
tmp.clear();
currWidth = ;
}
// room for extra blank
else
{
tmp.push_back(words[i]+" ");
currWidth += words[i].size()+;
}
}
}
// last line
if ( currWidth+words[words.size()-].size()>maxWidth )
{
// address words already in tmp
int blank = maxWidth - currWidth + ;
tmp.back() = tmp.back().substr(,tmp.back().size()-);
if ( tmp.size()> ){
int even = blank/(tmp.size()-);
for ( int k=; k<tmp.size()-; k++ ) tmp[k] = tmp[k] + string(even,' ');
int remain = blank%(tmp.size()-);
for ( int k=; k<remain; k++ ) tmp[k] = tmp[k] + " ";
string str = "";
for ( int k=; k<tmp.size(); ++k ) str += tmp[k];
ret.push_back(str);
}
else{
tmp[] = tmp[]+string(blank,' ');
ret.push_back(tmp[]);
}
// address the last line
blank = maxWidth - words[words.size()-].size();
ret.push_back(words[words.size()-]+string(blank,' '));
}
else
{
tmp.push_back(words[words.size()-]+string(maxWidth-currWidth-words[words.size()-].size(),' '));
string str = "";
for ( int k=; k<tmp.size(); ++k ) str += tmp[k];
ret.push_back(str);
}
return ret;
}
};

【Text Justification】cpp的更多相关文章

  1. hdu 4739【位运算】.cpp

    题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...

  2. Hdu 4734 【数位DP】.cpp

    题意: 我们定义十进制数x的权值为f(x) = a(n)*2^(n-1)+a(n-1)*2(n-2)+...a(2)*2+a(1)*1,a(i)表示十进制数x中第i位的数字. 题目给出a,b,求出0~ ...

  3. 【ZigZag Conversion】cpp

    题目: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows l ...

  4. 【Valid Sudoku】cpp

    题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...

  5. 【Permutations II】cpp

    题目: Given a collection of numbers that might contain duplicates, return all possible unique permutat ...

  6. 【Subsets II】cpp

    题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. ...

  7. 【Sort Colors】cpp

    题目: Given an array with n objects colored red, white or blue, sort them so that objects of the same ...

  8. 【Sort List】cpp

    题目: Sort a linked list in O(n log n) time using constant space complexity. 代码: /** * Definition for ...

  9. 【Path Sum】cpp

    题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...

随机推荐

  1. *5. Longest Palindromic Substring (dp) previous blogs are helpful

    Given a string s, find the longest palindromic substring in s. You may assume that the maximum lengt ...

  2. Selenium入门17 selenium IDE安装及使用

    selenium IDE是firefox浏览器的一个插件,支持脚本的录制回放,关键字驱动的.界面跟robotframework很像. 实际测试中不用录制回放,不过初学者拿来看看元素是如何定位的还是有用 ...

  3. dd-wrt ddns更新失败由于电信提供的ip不是公网ip

    由于电信提供的ip地址原来是公网的ip,后来电信通过nat提供一个内网ip,导致ddns更新失败.电话给电信客服10000号,让他们修改回来之后就可以了. 如果ddns更新失败,尤其是原本是正常的,后 ...

  4. OJ网站

    没事做做题是打发时间的好办法,还能练习下思维,效益很不错,但就是耗时 就选了3个oj,多了眼花缭乱 https://www.vijos.org/ http://uoj.ac/ https://leet ...

  5. 模拟水题,牛吃草(POJ2459)

    题目链接:http://poj.org/problem?id=2459 题目大意:有C头牛,下面有C行,每头牛放进草地的时间,每天吃一个草,总共有F1个草,想要在第D的时候,草地只剩下F2个草. 解题 ...

  6. 【[SDOI2017]新生舞会】

    题目 好题啊 我们要求的是 \[C=\frac{\sum_{i=1}^na_i}{\sum_{i=1}^nb_i}\] 使得\(C\)最大 显然 \[C\times \sum_{i=1}^nb_i=\ ...

  7. JavaEE权限管理系统的搭建(三)--------springmvc和mabatis整合环境搭建

    本节介绍如何环境的搭建和配置: 首先要在父工程引入jar包依赖: <!-- 通过属性定义指定jar的版本 --> <properties> <spring.version ...

  8. zen-Coding在Notepad++中的使用

    zen-Coding是一款快速编写HTML,CSS(或其他格式化语言)代码的编辑器插件,这个插件可以用缩写方式完成大量重复的编码工作,是web前端从业者的利器. zen-Coding插件支持多种编辑器 ...

  9. Java开发.gitignore文件包含.iml,.log的看法

    有一个开源项目https://github.com/github/gitignore 主要用来规范所有开发项目的.gitignore文件的编写,基本涵盖了所有的开发语言.开发环境等.今日我向JetBr ...

  10. python基础数据类型之字典的操作

    一. 字典的简单介绍字典(dict)是python中唯一的一个映射类型.他是以{ }括起来的键值对组成. 在dict中key是唯一的. 在保存的时候, 根据key来计算出一个内存地址. 然后将key- ...