【Text Justification】cpp
题目:
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.
- 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的更多相关文章
- hdu 4739【位运算】.cpp
题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...
- 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~ ...
- 【ZigZag Conversion】cpp
题目: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows l ...
- 【Valid Sudoku】cpp
题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...
- 【Permutations II】cpp
题目: Given a collection of numbers that might contain duplicates, return all possible unique permutat ...
- 【Subsets II】cpp
题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. ...
- 【Sort Colors】cpp
题目: Given an array with n objects colored red, white or blue, sort them so that objects of the same ...
- 【Sort List】cpp
题目: Sort a linked list in O(n log n) time using constant space complexity. 代码: /** * Definition for ...
- 【Path Sum】cpp
题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...
随机推荐
- 模拟停车POJ(3505)
题目链接:http://poj.org/problem?id=3505 解题报告: #include <stdio.h> #include <iostream> #includ ...
- P1316 丢瓶盖
题目描述 陶陶是个贪玩的孩子,他在地上丢了A个瓶盖,为了简化问题,我们可以当作这A个瓶盖丢在一条直线上,现在他想从这些瓶盖里找出B个,使得距离最近的2个距离最大,他想知道,最大可以到多少呢? 输入输出 ...
- 2018.8.18 servlet使用的会话跟踪除session外还有哪些方式
解释HTTP HTTP是一种无连接的协议,如果一个客户端只是单纯地请求一个文件(HTML或GIF),服务器端可以响应给客户端,并不需要知道一连串的请求是否来自于相同的客户端,而且也不需要担心客户端是否 ...
- MapReduce执行jar练习
1.用程序生成输入文件1.txt和2.txt 生成程序源码如下: https://www.cnblogs.com/jonban/p/10555364.html 2. 上传文件到hdfs文件系统 创建 ...
- nuget打包
[1.创建.nuspec文件] 在.csproj目录下运行命令 nuget spec [2.生成包nupkg] 在.csproj目录下运行命令 nuget pack xxxx.csproj [推送命令 ...
- javascript入门笔记8-window对象
History 对象 history对象记录了用户曾经浏览过的页面(URL),并可以实现浏览器前进与后退相似导航的功能. 注意:从窗口被打开的那一刻开始记录,每个浏览器窗口.每个标签页乃至每个框架,都 ...
- view的superview的变换
今天遇到一个奇怪的问题,一个view(称为subview)被加在了一个cell(superView1)上,然后创建了一个view(为superView2),将subview重新加在了superView ...
- spring-mybatis整合项目 异常处理2
org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'com/imooc ...
- MySQL 5.7传统复制到GTID在线切换(一主一从)
Preface Classic replication is commonly used in previous version of MySQL.It's really tough in ...
- 微信小程序开发入门学习(2):小程序的布局
概述 小程序的布局采用了和Css3中相同的 flex(弹性布局)方式,使用方法也类似(只是属性名不同而已). 水平排列 默认是从左向右水平依次放置组件,从上到下依次放置组件. 任何可视组件都需要使用样 ...