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

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.

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.

将由单词组成的数组,按每行最多L个字符进行对齐调整。

解法:先找到某一行能放下的单词,单词的字母数之和加上单词之间的空格要小于等于L,然后需要补充空格的话在填进去空格。假设有n个单词,那么就会有n-1个间隔,每个间隔的空格数应该是:(L-此行所有单词的长度和)/(n-1)。只用一个单词的话,排好单词在补上空格即可。

参考:喜刷刷

Java:

public List<String> fullJustify(String[] words, int L) {
List<String> res = new ArrayList<>();
int n = words.length;
char[] spaces = new char[L];
Arrays.fill(spaces, ' ');
for(int i=0; i<n; i++) {
int len = words[i].length();
int j = i;
while(i<n-1 && len+1+words[i+1].length()<=L) {
len += 1+words[++i].length();
}
StringBuilder sb = new StringBuilder(words[j]);
if(j == i || i==n-1) {
while(i==n-1 && j < i) {
sb.append(" "+words[++j]);
}
sb.append(spaces, 0, L-sb.length());
} else {
int avg = (L-len)/(i-j);
int rem = (L-len)%(i-j);
while(j < i) {
sb.append(spaces, 0, avg+1);
if(rem-- > 0) sb.append(" ");
sb.append(words[++j]);
}
}
res.add(sb.toString());
}
return res;
}  

Python:

class Solution(object):
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
def addSpaces(i, spaceCnt, maxWidth, is_last):
if i < spaceCnt:
# For the last line of text, it should be left justified,
# and no extra space is inserted between words.
return 1 if is_last else (maxWidth // spaceCnt) + int(i < maxWidth % spaceCnt)
return 0 def connect(words, maxWidth, begin, end, length, is_last):
s = [] # The extra space O(k) is spent here.
n = end - begin
for i in xrange(n):
s += words[begin + i],
s += ' ' * addSpaces(i, n - 1, maxWidth - length, is_last),
# For only one word in a line.
line = "".join(s)
if len(line) < maxWidth:
line += ' ' * (maxWidth - len(line))
return line res = []
begin, length = 0, 0
for i in xrange(len(words)):
if length + len(words[i]) + (i - begin) > maxWidth:
res += connect(words, maxWidth, begin, i, length, False),
begin, length = i, 0
length += len(words[i]) # Last line.
res += connect(words, maxWidth, begin, len(words), length, True),
return res  

C++:

class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
int cnt = 0, left = 0;
vector<string> result;
for(int i =0; i< words.size(); i++)
{
cnt += words[i].size();
if(cnt+i-left > maxWidth || i+1==words.size())
{
if(cnt+i-left > maxWidth) cnt -= words[i--].size();
string str = words[left];
for(int j = left+1; j<= i; j++)
{
int m = maxWidth-cnt, n = i-left;
if(i+1==words.size()) str += " ";
else str.append(m/n + (j-left-1<m % n), ' ');
str += words[j];
}
str.append(maxWidth-str.size(), ' ');
result.push_back(str);
left = i+1, cnt = 0;
}
}
return result;
}
};

  

All LeetCode Questions List 题目汇总

[LeetCode] 68. Text Justification 文本对齐的更多相关文章

  1. [leetcode]68. Text Justification文字对齐

    Given an array of words and a width maxWidth, format the text such that each line has exactly maxWid ...

  2. leetcode@ [68] Text Justification (String Manipulation)

    https://leetcode.com/problems/text-justification/ Given an array of words and a length L, format the ...

  3. [Leetcode] text justification 文本对齐

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

  4. Text Justification,文本对齐

    问题描述:把一个集合的单词按照每行L个字符放,每行要两端对齐,如果空格不能均匀分布在所有间隔中,那么左边的空格要多于右边的空格,最后一行靠左对齐. words: ["This", ...

  5. Leetcode#68 Text Justification

    原题地址 没有复杂的算法,纯粹的模拟题 先试探,计算出一行能放几个单词 然后计算出单词之间有几个空格,注意,如果空格总长度无法整除空格数,前面的空格长度通通+1 最后放单词.放空格,组成一行,加入结果 ...

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

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

  7. 【一天一道LeetCode】#68. Text Justification

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...

  8. Text Justification 文本左右对齐

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

  9. 【LeetCode】68. Text Justification

    Text Justification Given an array of words and a length L, format the text such that each line has e ...

随机推荐

  1. kali 攻击wordpress + trunkey linux wordpress 安装方法

    Kali-linux攻击WordPress和其他应用程序   今天越来越多的企业利用SAAS(Software as a Service)工具应用在他们的业务中.例如,他们经常使用WordPress作 ...

  2. Codeforces B. Minimum Possible LCM(贪心数论)

    题目描述: B. Minimum Possible LCM time limit per test 4 seconds memory limit per test 1024 megabytes inp ...

  3. python笔记38-使用zmail发各种邮件案例代码

    前言 本篇介绍使用zmail发各种格式的邮件,并运行成功的代码,小伙伴们只需更换自己的邮箱就可以运行起来了 content_text发送纯文本 先从最简单的发送纯文本的邮件开始,调通发送邮件的代码. ...

  4. myBatis框架之入门(四)

    Mybatis多表管理查询 多表关联关系分析: 多表关联:至少两个表关联.分析多表关系的经验技巧:从一条记录出发,不要从表整体去分析,比如分析A表和B表关系,A表中的一条记录对应B表中的几条记录,如果 ...

  5. 动态创建自绘的CListBox注意事项

    Create(WS_VISIBLE|WS_CHILD|LBS_NOTIFY|LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT ,rcWnd, ...

  6. wecenter系统关于标题及seo的修改

    wecenter整个系统好像根本就没有考虑过SEO优化,就连Title的识别也是随意的许多,在使用这个cms来完成我们自己的需求的时候,适当的修改是比不可少的.下面说说title标题修改方法. 今天分 ...

  7. 查询响应慢,DB近乎崩溃

    时间:18.11.22 一. 起由: 公司最近因业务,有大量注册,每天大约几万,貌似也不太高? 晚上8点左右,网站后台,前台突然大面积提示502.网站几乎瘫痪.买的阿里云的负载均衡和读写分离.分别是5 ...

  8. dimensionality reduction动机---visualization(将数据可视化帮助我们更好地理解数据)

    如果我们能更好地理解我们的数据,这样会对我们开发高效的机器学习算法有作用,将数据可视化(将数据画出来能更好地理解数据)出来将会对我们理解我们的数据起到很大的帮助. 高维数据如何进行显示 GDP: gr ...

  9. [bzoj 4176] Lucas的数论 (杜教筛 + 莫比乌斯反演)

    题面 设d(x)d(x)d(x)为xxx的约数个数,给定NNN,求 ∑i=1N∑j=1Nd(ij)\sum^{N}_{i=1}\sum^{N}_{j=1} d(ij)i=1∑N​j=1∑N​d(ij) ...

  10. LeetCode 881. Boats to Save People

    原题链接在这里:https://leetcode.com/problems/boats-to-save-people/ 题目: The i-th person has weight people[i] ...