题目:

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. 二进制安装mysql5.6

    安装依赖包  yum install -y libaio yum install -y perl perl-devel       解压   mkdir /opt/mysql mv mysql-5.6 ...

  2. Android(java)学习笔记62:android.intent.action.MAIN 与 android.intent.category.LAUNCHER 理解

    1. 先看看网路上的说法: android.intent.action.MAIN 决定应用程序最先启动的 Activity android.intent.category.LAUNCHER 决定应用程 ...

  3. 2017.10.28 针对Java Web应用中错误异常处理方法的运用

    针对Java Web应用中错误异常处理方法的运用 在javaweb中其异常都需要对Checked Exception之下的Exception进行继承,并且有选择地对发生的错误和异常进行处理.Java同 ...

  4. Visual Studio 2013 ReportViewer Control

    最近需要给学生讲报表,.NET的自然就是选择RDLC了. 因为学生比赛是用Visual Studio 2013,所以我在自己的笔记本上安装了Visual Studio 2013(平常是用2010),安 ...

  5. phpMyAdmin提示找不到mcrypt和mbstring模块

    yum install php-mcryptyum install php-mbstringphp -m 查看是否安装成功 service httpd restart 重启服务器 注: 这里可能会出现 ...

  6. mybatis-generator的maven插件使用异常(mybatis-generator-maven-plugin):generate failed: Exception getting JDBC Driver

    使用mybatis的代码生成工具:mybatis-generator,在父model中引入了maven插件的依赖,如下: <!-- Mybatis.generator插件 --> < ...

  7. Python的socket编程

    我们知道两个进程如果需要进行通讯最基本的一个前提能能够唯一的标示一个进程,在本地进程通讯中我们可以使用PID来唯一标示一个进程,但PID只在本地唯一,网络中的两个进程PID冲突几率很大,这时候我们需要 ...

  8. JavaScript模拟Form提交

    在一个系统跳转到另外一个系统中时,可以用WAS的全局安全性,也可以用共享session做单点登陆,这次接触到了js模拟form提交的方式. function loginOAForm(url) { va ...

  9. datatable行内内容太长,有时不自动换行解决方法

    加一个css属性即可 style = "word-wrap:break-word;" js代码: "render": function (data, type, ...

  10. Java OOP——第五章 异常

    1. 尝试通过if-else来解决异常问题: Eg: public class Test2 {       public static void main(String[] args) {       ...