[Leetcode 68, Hard] Text Justification
来源:互联网 发布:广州男装网络批发 编辑:程序博客网 时间:2024/09/21 08:56
Problem:
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.
click to show 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.
Analysis:
The solution comes from http://blog.csdn.net/kenden23/article/details/17376113
Solutions:
C++:
vector<string> fullJustify(vector<string>& words, int maxWidth) { vector<string> rs; int L = maxWidth; for (int i = 0; i < words.size(); ) { int j = i+1; int len = words[i].length(); for (; j < words.size() && len+words[j].length()<L; j++) len += 1 + words[j].length(); if (j == words.size()) { string s(words[i]); for (i++ ; i < j; i++) s +=" "+words[i]; while (s.length() < L) s.push_back(' '); rs.push_back(s); return rs; } if (j-i == 1) { rs.push_back(words[i++]); rs.back().append(L-rs.back().length(), ' '); continue; } int a = (L-len) / (j-i-1) + 1; int b = (L-len) % (j-i-1); string s(words[i]); for (i++; i < j; i++, b--) { s.append(a,' '); if (b>0) s.push_back(' '); s.append(words[i]); } rs.push_back(s); } return rs; }Java:
Python:
- [Leetcode 68, Hard] Text Justification
- Hard 68题 Text Justification
- LeetCode 68 Text Justification
- [leetcode 68] Text Justification
- leetcode 68 :Text Justification
- leetcode 68: Text Justification
- Leetcode 68 Text Justification
- LeetCode 68 -Text Justification
- LeetCode 68 Text Justification
- leetcode-68 Text Justification
- LeetCode 68 Text Justification
- LeetCode 68 Text Justification
- [leetcode-68]Text Justification(java)
- LeetCode(68) Text Justification
- leetcode hard模式专杀之68. Text Justification
- LeetCode 68 Text Justification (字符串格式处理)
- LeetCode-68-Text Justification 细节题
- LeetCode : Text Justification
- Web服务器Nginx+PHP&DB服务器mysql主从(新手)-1.DB服务器配置
- 暑假习题 四
- java学习
- Twelves Monkeys (multiset解法 141 - ZOJ Monthly, July 2015 - H)
- 珍惜
- [Leetcode 68, Hard] Text Justification
- 29个你必须知道的Linux命令
- 简单并查集之Wireless Network
- 最近工作:封装组件
- 师哥讲课的一些名词理解(查询整理)
- 1000 A + B Problem
- 很重要的EXCEL使用技巧
- 数组的应用OC
- hihocoder 1191 小W与网格 (组合数)