LeetCode 068 Text Justification
2015-10-05 16:57
309 查看
题目描述
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.
代码
[code] String space(int len) { char[] s = new char[len]; Arrays.fill(s, ' '); return new String(s); } public List<String> fullJustify(String[] words, int L) { ArrayList<String> text = new ArrayList<String>(); int p = 0; int lastp = 0; while (p < words.length) { if (L == 0 && "".equals(words[p])) { text.add(""); p++; continue; } int l = 0; while (l < L && p < words.length) { l += words[p++].length() + 1; } if (l - 1 > L) l -= words[--p].length() + 1; int count = p - lastp; int left = L - l + count; int add; if (count == 1) add = left; else if (p - 1 == words.length - 1) { add = 1; left = count - 1; } // fuck... else add = left / (count - 1); left -= add * (count - 1); String s = ""; for (int i = lastp; i < p - 1; i++) { if (left > 0) { s += words[i] + space(add + 1); left--; } else { s += words[i] + space(add); } } left = L - s.length() - words[p - 1].length(); if (count == 1 || p - 1 == words.length - 1) // fuck... s += words[p - 1] + space(left); else s += space(left) + words[p - 1]; text.add(s); lastp = p; } return text; }
相关文章推荐
- GCD的认识和使用
- sk_buff 里的len, data_len, skb_headlen
- cocos代码研究(6)有限时间动作类(FiniteTimeAction)学习笔记
- 二维数组的查找
- 第四周实践项目2-建立单链表算法库
- 第四周 项目6—多项式求和
- apt的引用
- 第四周项目3-单链表的应用逆置
- 第4周 项目3 - 单链表应用(2)
- HDOJ1016.Prime Ring Problem
- 数据挖掘复习 回归2
- 开始学Java,
- 第4周、项目3(3)—单链表应用-递增
- 第3周项目4 顺序表应用问题(1)
- [237]Delete Node in a Linked List
- 第四周项目3--单链表应用(3)
- 想开网店?向你推荐最好的开源电子商务平台
- Ubuntu 14.04鼠标光标狂闪问题
- UVA 11027 - Palindromic Permutation
- pom.xml解析