LeetCode 068 Text Justification
来源:互联网 发布:sql别名的范围 编辑:程序博客网 时间:2024/05/26 15:57
题目描述
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.
代码
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; }
- LeetCode: Text Justification [068]
- LeetCode 068 Text Justification
- LeetCode 068 Text Justification
- leetcode 068 —— Text Justification
- leetcode解题方案--068--Text Justification
- 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
- HDOJ1016.Prime Ring Problem
- 二维数组的查找
- 第六周项目1 - 建立顺序栈算法库
- OpenCV 学习(像素操作 2)
- 第四周 项目2 建立“单链表”的算法库
- LeetCode 068 Text Justification
- 第4周 项目3 - 单链表应用(3)
- POJ 3267 The Cow Lexicon (简单DP)
- boost之scoped_array的使用
- 【栈项目1 - 建立顺序栈算法库 第六周】
- HDU 5497 Inversion(树状数组求逆序对)
- 【第4周 项目6 - 多项式求和】
- 第6周项目2—建立链栈算法库
- 数据结构【线性表(二)链表】项目之多项式求和