leetcode
来源:互联网 发布:如何设置广电网络网线 编辑:程序博客网 时间:2024/06/06 12:52
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:
public List<String> fullJustify(String[] words, int maxWidth) { List<String> result = new ArrayList<>(); if (words.length == 1 && words[0].equals("") && maxWidth == 0) { result.add(""); return result; } for (int i = 0, use, len; i < words.length; i += use) { for (len = 0, use = 0; i + use < words.length && words[i + use].length() + len <= maxWidth - use; use++) { len += words[i + use].length(); } StringBuilder sb = new StringBuilder(); sb.append(words[i]); for (int j = 0; j < use - 1; j++) { if (i + use >= words.length) { sb.append(" "); } else { for (int m = (maxWidth - len) / (use - 1) + (j < (maxWidth - len) % (use - 1) ? 1 : 0); m > 0; m--) { sb.append(" "); } } sb.append(words[i + j + 1]); } for (int m = maxWidth - sb.length(); m > 0; m--) { sb.append(" "); } result.add(sb.toString()); } return result; }
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- RTMP推流及协议学习
- GBK到UTF8编码转换C++实现
- 【图像处理】Apple Tags
- javascript 数组 深拷贝的简易方法(通过concat)
- 机器人操作系统ROS Indigo 入门学习(9)——理解ROS rqt_console和 roslaunch
- leetcode
- G++ 中文使用教程
- 垃圾收集分析(1)-Java对象结构(上)
- 数字营销公司HubSpot成功的9个经验
- 导致MyEclipse内存不足的原因分析及解决办法
- 自定义MarketCircleView控件,实现圆环
- leetcode
- Scala 基础入门教程
- 自己编写makefile