LeetCode Text Justification
来源:互联网 发布:java 图片相似度对比 编辑:程序博客网 时间:2024/06/05 14:37
LeetCode解题之Text Justification
原题
把一个集合的单词按照每行L个字符存放,不足的在单词间添加空格,每行要两端对齐(即两端都要是单词),如果空格不能均匀分布在所有间隔中,那么左边的空格要多于右边的空格,最后一行靠左对齐,每个单词间一个空格。
注意点:
- 单词的顺序不能发生改变
- 中间行也可能出现只有一个单词,这时要靠左对齐
- 每行要尽可能多的容纳单词
例子:
输入: words = [“This”, “is”, “an”, “example”, “of”, “text”, “justification.”], maxWidth = 16
输出:
[ "This is an", "example of text", "justification. "]
解题思路
这道题比较繁琐,题目就一大段。采用双指针的方法来标记当前行的单词,如果加上下一个单词的长度和每个单词间至少一个空格时的总长度大于目标长度,说明此时的单词就是该行应该存放的。要分是否只有一个单词还是多个单词进行讨论,如果有多个单词,需要平均分配单词间的空格。现在可以知道总的空格数和单词间隔数,所以计算单词间的间隔比较简单,注意多余的空格要优先添加到左边的单词间隔中。不要忘记添加最后一行的单词。
AC源码
class Solution(object): def fullJustify(self, words, maxWidth): """ :type words: List[str] :type maxWidth: int :rtype: List[str] """ start = end = 0 result, curr_words_length = [], 0 for i, word in enumerate(words): if len(word) + curr_words_length + end - start > maxWidth: if end - start == 1: result.append(words[start] + ' ' * (maxWidth - curr_words_length)) else: total_space = maxWidth - curr_words_length space, extra = divmod(total_space, end - start - 1) for j in range(extra): words[start + j] += ' ' result.append((' ' * space).join(words[start:end])) curr_words_length = 0 start = end = i end += 1 curr_words_length += len(word) result.append(' '.join(words[start:end]) + ' ' * (maxWidth - curr_words_length - (end - start - 1))) return resultif __name__ == "__main__": assert Solution().fullJustify(["This", "is", "an", "example", "of", "text", "justification."], 16) == [ "This is an", "example of text", "justification. " ]
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
0 0
- LeetCode : Text Justification
- [LeetCode] Text Justification
- leetcode 103: Text Justification
- [LeetCode]Text Justification
- [leetcode] Text Justification
- Text Justification leetcode
- Leetcode: Text Justification
- leetcode Text Justification
- LeetCode Text Justification
- LeetCode | Text Justification
- LeetCode Text Justification
- [Leetcode] Text Justification (Java)
- LeetCode OJ:Text Justification
- Leetcode: Text Justification
- [LeetCode] Text Justification
- 【LeetCode】Text Justification
- Text Justification -- LeetCode
- LeetCode: Text Justification [068]
- VS2013+CnComm串口通讯
- c++ stack和queue
- iOS下载大文件原理解析一
- 图标设计工具 IconWorkshop v6.3.3汉化绿色版
- SQL 查询 日期
- LeetCode Text Justification
- 隐藏状态栏
- Yarn资源分配性能调优
- Sona
- 复杂对象的组装与创建——建造者模式
- 其实你不知道MultiDex到底有多坑
- 蓝桥网 基础练习 完美的代价
- PyQt学习笔记02-drag & drop
- HTML中select选择菜单跳转“当前窗口”或“新窗口”