LeetCode: Text Justification 解题报告
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的解法。
以下是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 解题报告的更多相关文章
- LeetCode: Combination Sum 解题报告
Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...
- [leetcode]Text Justification @ Python
原题地址:https://oj.leetcode.com/problems/text-justification/ 题意: Given an array of words and a length L ...
- 【LeetCode】Permutations 解题报告
全排列问题.经常使用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. ...
- [LeetCode] Text Justification 文本左右对齐
Given an array of words and a length L, format the text such that each line has exactly L characters ...
- LeetCode - Course Schedule 解题报告
以前从来没有写过解题报告,只是看到大肥羊河delta写过不少.最近想把写博客的节奏给带起来,所以就挑一个比较容易的题目练练手. 原题链接 https://leetcode.com/problems/c ...
- LeetCode:Text Justification
题目链接 Given an array of words and a length L, format the text such that each line has exactly L chara ...
- LeetCode: Sort Colors 解题报告
Sort ColorsGiven an array with n objects colored red, white or blue, sort them so that objects of th ...
- [Leetcode] text justification 文本对齐
Given an array of words and a length L, format the text such that each line has exactly L characters ...
- [LeetCode] Text Justification words显示的排序控制
Given an array of words and a length L, format the text such that each line has exactly L characters ...
随机推荐
- 对UserDict的研究
# -*- coding: utf-8 -*- #python 27 #xiaodeng #对UserDict的研究 class UserDict(): def __init__(self, dict ...
- java 加密工具(产生证书)
给Tomcat服务器应用加密: 命令:keytool -genkey -alias tomcat -keyalg RSA -genkey产生密钥对 -alias取得别名 -keyalg RSA产生密钥 ...
- 如何架设部署V2EX社区/论坛(Google App Engine版)
1.What's V2EX? 关于这个问题,我们可以看看其作者Livid早期自己的V2EX社区的介绍: What's V2EX? 这是很多人都问过的问题,而我一直都没有做出一个明确的解答.因为我实在觉 ...
- HDUOJ---1213How Many Tables
How Many Tables Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) ...
- iOS 网络编程 TCP/UDP HTTP
一.HTTP协议的主要特点: 1. CS模式 2. 简单快速:只需要传送请求方法和路径.(常用方法有GET,HEAD,POST) 3. 灵活:任意对象都可以,类型由Content-Type加以标记 4 ...
- linux命令中的 < 和 |、>符号作用就解释
输出重定向比如输入一条命令,默认行为是将结果输出到屏幕.但有时候我们需要将输出的结果保存到文件,就可以用重定向.ps > ps.txt < 表示的是输入重定向的意思,就是把<后面跟的 ...
- 非微信内如何调起wap版微信支付
微信支付一直没有出wap版,wap版想用微信支付,只有在微信内调用才可以.今天偶然发现,中国电信一个wap站点, 不在微信内也能调起微信支付,而且官方还提供了一个demo. WAP怎么调起客户端? 在 ...
- Spring MVC+Mybatis 执行存储过程,使用Map进行参数的传递
研究了一天mybatis如何执行存储过程,基本了解了ORM的设计思想,在map层面进行对象关系映射有两种思路. 根据不同的业务使用不同的思路: 一.实体类和数据库映射,就是将数据库中的字段和java实 ...
- 转multicast vs broadcast
转自:http://blog.csdn.net/bloghome/article/details/4682984 一.multicast概述: 多媒体应用集成了声音.图形.动画.文本以及视频,这种 ...
- OAF_OAF Framework常用函数汇总(概念)
2014-12-31 Created By BaoXinjian