代码拉取完成,页面将自动刷新
package leetcode_1To300;
import java.util.ArrayList;
import java.util.List;
/**
* 本代码来自 Cspiration,由 @Cspiration 提供
* 题目来源:http://leetcode.com
* - Cspiration 致力于在 CS 领域内帮助中国人找到工作,让更多海外国人受益
* - 现有课程:Leetcode Java 版本视频讲解(1-900题)(上)(中)(下)三部
* - 算法基础知识(上)(下)两部;题型技巧讲解(上)(下)两部
* - 节省刷题时间,效率提高2-3倍,初学者轻松一天10题,入门者轻松一天20题
* - 讲师:Edward Shi
* - 官方网站:https://cspiration.com
* - 版权所有,转发请注明出处
*/
public class _68_TextJustification {
/**
* 68. 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. "
]
time : O(n)
space : O(n)
* @param words
* @param L
* @return
*/
public List<String> fullJustify(String[] words, int L) {
List<String> res = new ArrayList<>();
int index = 0;
while (index < words.length) {
int count = words[index].length();
int last = index + 1;
while (last < words.length) {
if (words[last].length() + count + 1 > L) break;
count += 1 + words[last].length();
last++;
}
StringBuilder builder = new StringBuilder();
builder.append(words[index]);
int diff = last - index - 1;
if (last == words.length || diff == 0) {
for (int i = index + 1; i < last; i++) {
builder.append(" ");
builder.append(words[i]);
}
for (int i = builder.length(); i < L; i++) {
builder.append(" ");
}
} else {
int spaces = (L - count) / diff;
int r = (L - count) % diff;
for (int i = index + 1; i < last; i++) {
for (int k = spaces; k > 0; k--) {
builder.append(" ");
}
if (r > 0) {
builder.append(" ");
r--;
}
builder.append(" ");
builder.append(words[i]);
}
}
res.add(builder.toString());
index = last;
}
return res;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。