【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 ...
随机推荐
- java——栈和队列 面试题
(1)栈的创建 (2)队列的创建 (3)两个栈实现一个队列 (4)两个队列实现一个栈 (5)设计含最小函数min()的栈,要求min.push.pop.的时间复杂度都是O(1) (6)判断栈的push ...
- Hybris开发环境的license计算实现
每隔30天,必须重新执行一次initialize命令把本地所有数据全部清掉然后重新build,需要花费一些时间. 显示在console里的license信息通过license.jsp展示: 剩余的li ...
- 过河问题(POJ1700)
题目链接:http://poj.org/problem?id=1700 解题报告: 1.贪心算法,每次过两个速度最慢的人,抵消那个较慢的人的时间. #include <stdio.h> # ...
- Java从入门到放弃——02.常量、变量、数据类型、运算符
本文目标 理解什么是常量,什么是变量 认识八大基本数据类型 了解算数运算符.赋值运算符.关系运算符.逻辑运算符.位运算符.三元运算符 1.什么是常量与变量? 常量是相对静止的量,比如整数:1,2,3 ...
- ios相关配置
Deployment Target,它控制着运行应用需要的最低操作系统版本.
- mysql关键字了解
unsigned 无符号 就是没有负数 列-1 -2 auto_increment 自增 comment 注释 primary key 主键 foreign key () references ...
- 散度(Divergence)和旋度(Curl)
原文链接 散度(Divergence) 散度的讨论应从向量和向量场说起.向量是数学中研究多维计算的基本概念.比如,速度可以分解为相互独立的分量,则速度就是一个多维的向量.假如空间中的每一个位置都有一个 ...
- java并发多线程(摘自网络)
1. 进程和线程之间有什么不同? 一个进程是一个独立(self contained)的运行环境,它可以被看作一个程序或者一个应用.而线程是在进程中执行的一个任务.Java运行环境是一个包含了不同的类和 ...
- 当Java遇见了Html--Servlet篇
###一.什么是servlet servlet是在服务器上运行的小程序.一个servlet就是一个 java类,并且通过"请求-响应"编程模型来访问的这个驻留在服务器内存里的程序. ...
- jquery 筛选元素 (3)
.addBack() 添加堆栈中元素集合到当前集合中,一个选择性的过滤选择器. .addBack([selector]) selector 一个字符串,其中包括一个选择器表达式,匹配当前元素集合,不包 ...