题目

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. ”

]

分析

给定一个字符串数组以及规定长度,按规则将其分组输出;

题目本身是不难的,主要是规则繁杂:

  1. 首先,输出以是否为末行分为两类;
  2. 对于非末行单词组,又以其包含的单词个数分为两类,一是单个单词,二是多个单词;

第一步,讨论非末行单词组合:

(1)若该组只包含一个单词,规定其左对齐,不足指定长度以空格填充;

(2)若该组包含count个单词,那么它有(count-1)个间隔,每个间隔放置一个空格;此时,求出不足指定长度需要的额外空格数目,extraSpace,每个单词间隔填充extra/(count-1)个空格;此时,若不整除那么前extra%(count-1)个间隔再次填充一个空格;

第二步,讨论末行单词组合:

(1)若只有一个单词,左对齐,不足指定长度以空格填充;

(2)若该组有count个单词,那么它有(count-1)个间隔,每个间隔放置一个空格;不足指定长度,末尾填充;

AC代码

class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
if (words.empty())
return vector<string>();
vector<string> ret; int sz = words.size(); /*sumLen记录当前字符串长度,count记录包含的单词个数*/
vector<string> tmp;
int sumLen = 0, count = 0;
for (int i = 0; i < sz; ++i)
{
/*判断是否可以添加一个字符串*/
if ((sumLen + words[i].length() + count) <= maxWidth)
{
/*满足要求,单词个数增一,保存*/
++count;
sumLen = sumLen + words[i].length();
tmp.push_back(words[i]);
continue;
}//if
else{
/*只有一个单词,左对齐*/
if (1 == count)
{
string str = tmp[0];
while (str.length() < maxWidth)
str += " ";
ret.push_back(str);
}//if
else{
string str = "";
/*计算多余的空格总数,每个间隔至少一个空格*/
int extraSpace = maxWidth - sumLen - count + 1;
/*每个间隔需再增加的间隔*/
int everySpace = extraSpace / (count - 1);
/*前间隔需要额外放置一个空格的间隔数*/
int frontSpace = extraSpace % (count - 1); for (int k = 0; k < count - 1; ++k)
{
int j = 0;
while (j < everySpace + 1)
{
tmp[k] += " ";
++j;
}//while
}//for
/*前frontSpace个间隔需要再放一个空格*/
for (int k = 0; k < frontSpace; ++k)
{
tmp[k] += " ";
}
/*连接这些字符串*/
for (int k = 0; k < count; ++k)
{
str += tmp[k];
}//for
ret.push_back(str);
}//else
}//else
tmp.clear();
count = 0;
sumLen = 0;
--i;
}//for
/*处理最后一组,也就是尾行*/
/*只有一个单词,左对齐*/
if (1 == count)
{
string str = tmp[0];
while (str.length() < maxWidth)
str += " ";
ret.push_back(str);
}//if if(count > 1){
string str = "";
/*末行的每个单词间放一个空格,其余空格放在尾部*/
for (int k = 0; k < count - 1; ++k)
{
str = str + tmp[k] + " ";
}//for
str += tmp[count - 1];
while (str.length() < maxWidth)
str += " ";
ret.push_back(str);
}//else
return ret;
}
};

GitHub测试程序源码

LeetCode(68) Text Justification的更多相关文章

  1. LeetCode(68):文本左右对齐

    Hard! 题目描述: 给定一个单词数组和一个长度 maxWidth,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本. 你应该使用“贪心算法”来放置给定的单词:也就是 ...

  2. LeetCode(68)-Compare Version Numbers

    题目: Compare two version numbers version1 and version2. If version1 > version2 return 1, if versio ...

  3. Qt 学习之路 2(68):访问网络(4)

    Home / Qt 学习之路 2 / Qt 学习之路 2(68):访问网络(4) Qt 学习之路 2(68):访问网络(4) 豆子 2013年11月7日 Qt 学习之路 2 19条评论 前面几章我们了 ...

  4. LeetCode(275)H-Index II

    题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...

  5. LeetCode(220) Contains Duplicate III

    题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...

  6. LeetCode(154) Find Minimum in Rotated Sorted Array II

    题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...

  7. LeetCode(122) Best Time to Buy and Sell Stock II

    题目 Say you have an array for which the ith element is the price of a given stock on day i. Design an ...

  8. LeetCode(116) Populating Next Right Pointers in Each Node

    题目 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode * ...

  9. LeetCode(113) Path Sum II

    题目 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given ...

随机推荐

  1. Android中RelativeLayout各个属性的含义

    android:layout_above="@id/xxx"  --将控件置于给定ID控件之上android:layout_below="@id/xxx"  - ...

  2. centos 7 下安装Nginx

    下载Nginx wget nginx.tar.gz http://nginx.org/download/nginx-1.11.3.tar.gz 解压源码 .tar.gz 然后进入目录编译安装 cd n ...

  3. 通过SQL语句提取存储过程中的内容

    首先,列出服务器上所有数据库. -- 获取数据库列表 SELECT name FROM master.dbo.sysdatabases ORDER BY name 其次,这是一种让所有的用户从数据库中 ...

  4. XE6移动开发环境搭建之IOS篇(6):设置Mac OSX的网络。(有图有真相)

    网上能找到的关于Delphi XE系列的移动开发环境的相关文章甚少,本文尽量以详细的图文内容.傻瓜式的表达来告诉你想要的答案. 原创作品,请尊重作者劳动成果,转载请注明出处!!! 我们配置一下MAC的 ...

  5. AX Dynamic 2012 tabletype:TempDB使用

    LedgerJournalTmp ledgerJournalTmpJoin; LedgerJournalTransAccrual this.takeOwnershipOfTempTable(ledge ...

  6. 修复山寨版的J-Link

    Fixed J-Link 1. Erase   (1) Power On   (2) Jump "ERASE"(JP3)   (3) Wait for 5s   (4) Break ...

  7. HEAP CORRUPTION 错误

    一般是new一块内存过小,  在这个内存块上写入的内容过大, delete时出现的错误; 如: char* ptr = new char[2]; //申请了两个字节 *ptr = "1234 ...

  8. listed

    http://sebastianruder.com/optimizing-gradient-descent/ http://www.nag.co.uk/pss/nag-and-algorithmic- ...

  9. Jquery Datatables 请求参数及接收参数处理

    Jquery Datatables 请求参数及接收参数处理 /** * Created by wb-wuyifu on 2016/8/9. */ /** * Created by wb-wuyifu ...

  10. 远程操控软件 TeamViewer for MAC 官方中文版11.0.55321

    百度云:https://pan.baidu.com/s/1o77ol2y 提取密码:3tsx windows: http://download.pchome.net/internet/server/r ...