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. UVa 1303 - Wall

    题目:有非常多点.修一座最短的围墙把素有点围起来,使得全部点到墙的距离不小于l. 分析:计算几何,凸包. 假设.没有距离l的限制.则答案就是凸包的周长了.有了距离限制事实上是添加了2*π*l. 证明: ...

  2. try/except/else语句

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #Python学习手册 868 #try/except/else语句 #try语句分句形式 except: # ...

  3. RDD转换成DataFrames

    官方提供了2种方法 1.利用反射来推断包含特定类型对象的RDD的schema.这种方法会简化代码并且在你已经知道schema的时候非常适用. 先创建一个bean类 case class Person( ...

  4. 学习KNN

    转:© 著作权归作者所有 by ido 什么是KNN算法呢?顾名思义,就是K-Nearest neighbors Algorithms的简称.我们可能都知道最近邻算法,它就是KNN算法在k=1时的特例 ...

  5. C中字符串分割函数strtok的一个坑

    strtok的典型用法是: p = strtok(s4, split); while(p != NULL){ printf("%s\n", p); p = strtok(NULL, ...

  6. iOS10 完美降级 iOS9.3.2,保留全部数据

    本篇文章由:http://xinpure.com/downgrade-ios10-perfect-ios9-3-2-retention-of-all-data/ iOS 10 Beta版尝鲜 前段时间 ...

  7. leetcode719:直线上的第k近点对

    问题描述 给定数组a[N],可以确定C(N,2)个点对,也就确定了C(N,2)个距离,求这些距离中第k小的距离(k<C(N,2)). 思路 看到第k小.第k大这种问题,首先想到二分法. 把求值问 ...

  8. supervisor+gunicorn部署python web项目

    有了Nginx,对于Tomcat没有必要详细了解. 有了supervisor,再也没有必要把一个程序设置成服务.驻留进程,supervisor真是一个相见恨晚的好工具. 在Tomcat中,所有的web ...

  9. POJ 3233 Matrix Power Series (矩阵乘法)

    Matrix Power Series Time Limit: 3000MS   Memory Limit: 131072K Total Submissions: 11954   Accepted:  ...

  10. oracle中的一些基本概念

    Oracle数据库的物理文件是存储在磁盘上的数据文件.控制文件和日志文件的总称.数据文件和日志文件是数据库中最重要的文件.数据库由若干个表空间组成,表空间由表组成,表由段组成,段由区间组成,区间由数据 ...