【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 ...
随机推荐
- CRM, C4C和Hybris的后台作业
CRM 使用事务码SM36查看CRM系统的后台作业: 举一些例子: ABAP_TEXT_INDEX这个job执行的report是ABAP_DOCU_CREATE_TEXT_INDEX: 负责填充buf ...
- input,button制作按钮IE6,IE7点击时1px黑边框的解决方法
按钮在IE6中点击时1px黑边框的最常见的解决方法 首先设置按钮为none,然后在按钮外面套一层来实现边框的效果,部分代码如下 .btnbox{ border:solid 1px red;} .btn ...
- 获取url中的某个字段的值
function getUrl(name, url) { url = url || window.location.search; var reg = new RegExp("(^|& ...
- axure 动态面板实现图片轮播效果(淘宝)
淘宝中经常可以看到店铺中的图片轮播效果,本经验将通过axure7.0实现 工具/原料 axure7.0 方法/步骤 下载需要轮播的图片 将图片引入至axure中,将引入的第一张图片转为 ...
- jenkins 执行shell命令出错command not found 和No such file or directory
[root@localhost usr]# sh test.sh command not found -bash: cd: usr: No such file or directory 这里碰到了一个 ...
- 2017.11.4 JavaWeb-----基于JavaBean+JSP求任意两数代数和(改进的在JSP页面中无JSP脚本代码的)+网页计数器JavaBean的设计与使用
修改后的JSP中不含有JSP脚本代码这使得JSP程序的清晰性.简单 1.设计JavaBean 的Add.java 类 package beans; public class Add { private ...
- 第37章 基于SD卡的FatFs文件系统—零死角玩转STM32-F429系列
第37章 基于SD卡的FatFs文件系统 全套200集视频教程和1000页PDF教程请到秉火论坛下载:www.firebbs.cn 野火视频教程优酷观看网址:http://i.youku.co ...
- css3 子元素的的应用 注意点
已经第二次犯错误,不允许有下次 <ul class="ul"> <li> <a>哈哈</a> </li> <li& ...
- poj_3641_Pseudoprime numbers
Fermat's theorem states that for any prime number p and for any integer a > 1, ap = a (mod p). Th ...
- 01U盘PE系统制作方法
1. 需要的工具和安装包:WinPE镜像文件 WinPE_x86.iso .已制作好的另一个启动盘(下文以映像总裁为例,当然也可以使用大白菜.U启动等) . 电脑.准备制作PE系统的空U盘 2. 还原 ...