Text Justification

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.

SOLUTION 1:

递归解答:

每一次只处理一行,其它行交给下一级递归来处理。

思路是:

1. 先贪心法取得我们这一行可以放多少单词。

2. 在每个单词后面计算空格1个,但最后一个的要加回来。因为最后一个单词不需要加空格在右边。

3. 余下的空格数,平均分配给所有的interval。

4. 如果不能取整,多出的从左到右分配给那些interval。

5. 如果是1个单词,或是最后一行,在最后补空格。

其实整个题目不算难。但很繁杂,起码提交了8,9次才算过。

 public class Solution {
public List<String> fullJustify(String[] words, int L) {
List<String> ret = new ArrayList<String>(); if (words == null) {
return ret;
} rec(words, L, 0, ret);
return ret;
} public static void rec(String[] words, int L, int index, List<String> list) {
int len = words.length;
if (index >= len) {
return;
} int LenTmp = L; int end = index;
for (int i = index; i < len && words[i].length() <= L; i++) {
L -= words[i].length(); // the space follow the word.
L--;
end = i;
} // 最后一个空格收回
L++; // Count how many words do we have.
int num = end - index + 1; int extraSpace = 0;
int firstExtra = 0; // 单词数大于1,才需要分配,否则所有的空格加到最后即可
if (num > 1) {
extraSpace = L / (num - 1);
// 首单词后多跟的空格
firstExtra = L % (num - 1);
} StringBuilder sb = new StringBuilder();
for (int i = index; i <= end; i++) {
sb.append(words[i]); // The space following every word.
if (i != end) {
sb.append(' ');
} // 不是最后一行
if (end != len - 1) {
// The first words.
if (firstExtra > 0) {
sb.append(' ');
firstExtra--;
} // 最后一个单词后面不需要再加空格
if (i == end) {
break;
} // 每个单词后的额外空格
int cnt = extraSpace;
while (cnt > 0) {
sb.append(' ');
cnt--;
}
}
} // 最后一行的尾部的空格
int tailLen = LenTmp - sb.length();
while (tailLen > 0) {
sb.append(' ');
tailLen--;
} list.add(sb.toString());
rec(words, LenTmp, end + 1, list);
}
}

SOLUTION 2:

其实之前的递归是一个尾递归,我们可以很容易地把尾递归转化为Iteration的解法。

尾调用Wiki

以下是Iteration的解法:

思想是一致的。

 // SOLUTION 2: iteration.
public List<String> fullJustify(String[] words, int L) {
List<String> ret = new ArrayList<String>();
if (words == null) {
return ret;
} int len = words.length;
int index = 0; while (index < len) {
int LenTmp = L; int end = index;
for (int i = index; i < len && words[i].length() <= LenTmp; i++) {
LenTmp -= words[i].length(); // the space follow the word.
LenTmp--;
end = i;
} // 最后一个空格收回
LenTmp++; // Count how many words do we have.
int num = end - index + 1; int extraSpace = 0;
int firstExtra = 0; // 单词数大于1,才需要分配,否则所有的空格加到最后即可
if (num > 1) {
extraSpace = LenTmp / (num - 1);
// 首单词后多跟的空格
firstExtra = LenTmp % (num - 1);
} StringBuilder sb = new StringBuilder();
for (int i = index; i <= end; i++) {
sb.append(words[i]); // The space following every word.
if (i != end) {
sb.append(' ');
} // 不是最后一行
if (end != len - 1) {
// The first words.
if (firstExtra > 0) {
sb.append(' ');
firstExtra--;
} // 最后一个单词后面不需要再加空格
if (i == end) {
break;
} // 每个单词后的额外空格
int cnt = extraSpace;
while (cnt > 0) {
sb.append(' ');
cnt--;
}
}
} // 最后一行的尾部的空格
int tailLen = L - sb.length();
while (tailLen > 0) {
sb.append(' ');
tailLen--;
} ret.add(sb.toString());
index = end + 1;
} return ret;
}

SOLUTION 3:

参考http://www.ninechapter.com/solutions/text-justification/

在solution2的基础上进行了一些简化,把append word的函数独立出来,解答如下,更加简洁:

 // SOLUTION 3: iteration2
public List<String> fullJustify(String[] words, int L) {
List<String> ret = new ArrayList<String>();
if (words == null) {
return ret;
} int len = words.length;
int index = 0; while (index < len) {
int LenTmp = L; int end = index;
for (int i = index; i < len && words[i].length() <= LenTmp; i++) {
LenTmp -= words[i].length(); // the space follow the word.
LenTmp--;
end = i;
} // 最后一个空格收回
LenTmp++; // Count how many words do we have.
int num = end - index + 1; int extraSpace = 0;
int firstExtra = 0; // 单词数大于1,才需要分配,否则所有的空格加到最后即可
if (num > 1) {
extraSpace = LenTmp / (num - 1);
// 首单词后多跟的空格
firstExtra = LenTmp % (num - 1);
} StringBuilder sb = new StringBuilder();
for (int i = index; i <= end; i++) {
sb.append(words[i]); int cnt = 0; if (i == end) {
break;
} // 不是最后一行
if (end != len - 1) {
// The first words.
if (firstExtra > 0) {
cnt++;
firstExtra--;
} // 最后一个单词后面不需要再加空格
// 每个单词后的额外空格
cnt += extraSpace;
} // 1: 每个单词后本来要加的空格
appendSpace(sb, cnt + 1);
} // 最后一行的尾部的空格,或者是只有一个单词的情况
appendSpace(sb, L - sb.length()); ret.add(sb.toString());
index = end + 1;
} return ret;
} public void appendSpace(StringBuilder sb, int cnt) {
while (cnt > 0) {
sb.append(' ');
cnt--;
}
}

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/FullJustify.java

LeetCode: Text Justification 解题报告的更多相关文章

  1. LeetCode: Combination Sum 解题报告

    Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...

  2. [leetcode]Text Justification @ Python

    原题地址:https://oj.leetcode.com/problems/text-justification/ 题意: Given an array of words and a length L ...

  3. 【LeetCode】Permutations 解题报告

    全排列问题.经常使用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. ...

  4. [LeetCode] Text Justification 文本左右对齐

    Given an array of words and a length L, format the text such that each line has exactly L characters ...

  5. LeetCode - Course Schedule 解题报告

    以前从来没有写过解题报告,只是看到大肥羊河delta写过不少.最近想把写博客的节奏给带起来,所以就挑一个比较容易的题目练练手. 原题链接 https://leetcode.com/problems/c ...

  6. LeetCode:Text Justification

    题目链接 Given an array of words and a length L, format the text such that each line has exactly L chara ...

  7. LeetCode: Sort Colors 解题报告

    Sort ColorsGiven an array with n objects colored red, white or blue, sort them so that objects of th ...

  8. [Leetcode] text justification 文本对齐

    Given an array of words and a length L, format the text such that each line has exactly L characters ...

  9. [LeetCode] Text Justification words显示的排序控制

    Given an array of words and a length L, format the text such that each line has exactly L characters ...

随机推荐

  1. Storm简述及集群安装

    Storm 集群类似于一个 Hadoop 集群.然而你在 Hadoop 的执行"MapReduce job", 在storm 上你执行 "topologies (不好翻译 ...

  2. 〖Linux〗Ubuntu13.10 安装qt开发环境

    sudo apt-get install qtcreator libqt4-dev libqt4-dbg libqt4-gui libqt4-sql qt4-dev-tools qt4-doc qt4 ...

  3. oracl查询锁表语句

    技能源于生活的不断实践,实践是对知识的不断扩展和总结.汇总.进而形成思想体系! --查询锁表语句 select sess.sid, sess.serial#, lo.oracle_username, ...

  4. Hex棋

    Hex棋,又叫六角棋,译作海克斯棋.据说这个游戏是约翰·纳什发明的.网上并没有太多介绍,第一次听说是在"中国大学生计算机博弈大赛"官网上. 棋盘为11×11的六边形小格子组成,它是 ...

  5. java socket输入输出中文乱码问题

    http://hi.baidu.com/linjk03/item/e2028bfd990c14ea1a111feb 统一了输入输出的编码格式,是不会有乱码问题出现的.   构造Reader或Write ...

  6. 验证码在后台的编写,并实现点击验证码图片时时发生更新 C# 项目发布到IIS后不能用log4net写日志

    验证码在后台的编写,并实现点击验证码图片时时发生更新   验证码在软件中的地位越来越重要,有效防止这种问题对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试:下面就是实现验证码的基本步骤: ...

  7. 设置PdfPTable与标题间的距离

    使用itextsharp生成PDF时,需要改变标题与文档中添加的PdfPTable间距离,改变SpacingBefore值不起作用,查了下这方面的知识较少,自己跟踪代码,找到了设置位置是在使用iTex ...

  8. PS_Form个性化选择Block自动查询和查询条件排序实现(案例)

    2014-06-01 BaoXinjian

  9. Linux内核中锁机制之原子操作、自旋锁

    很多人会问这样的问题,Linux内核中提供了各式各样的同步锁机制到底有何作用?追根到底其实是由于操作系统中存在多进程对共享资源的并发访问,从而引起了进程间的竞态.这其中包括了我们所熟知的SMP系统,多 ...

  10. Python 字典 items() 方法

    描述 Python 字典 items() 方法以列表形式(并非直接的列表,若要返回列表值还需调用list函数)返回可遍历的(键, 值) 元组数组. 语法 items() 方法语法: D.items() ...