class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
// 1. 设计模拟人类思想
// 1.1 判断maxWidth能最多放几个单词(n)
// 1.2 maxWidth应该 > total(words[n].length())+ total.length - 1
// 1.3 实现方法就是一个一个去加来判断 等到再加下一个就超出maxWidth就停止循环判断
List<String> result = new ArrayList<>();
// 2.由于是分组的 所以把整个1步骤循环
// 定义一个遍历的指针
int position = 0;
while(position < words.length) {
// 已经有了几个单词和单词长度大小
int total = -1;
int totalWords = 0;
while(total <= maxWidth) {
if (position < words.length) {
// 单词加1
totalWords += 1;
// 长度加上这个单词长度 然后去判断是否超出 超出就回滚并return
total += 1 + words[position].length();
if (total > maxWidth) {
// 回滚操作
totalWords -= 1;
total -= 1 + words[position].length();
// 然后存储 存储position-1 到position-totalWords
String str = "";
// 处理分配空格问题
int spaces = maxWidth - (total - (totalWords -1));
// 一共多少个空字符串(几个空格位)
int item = totalWords - 1;
// 平均空格值
int base = 0;
try {
// 当item为 0就设置base为0
base = spaces / item;
} catch (Exception e) {
base = 0;
}
// 余了多少
int rest = spaces - base * item;
if (totalWords == 1) {
str += words[position-1];
for (int i = 0; i < rest; i++) {
str += " ";
}
result.add(str);
break;
}
// 前几个空字符串需要+1个空格 因为面临空字符串不均匀的问题
for(int i = position-totalWords, flag = 0; i <= position-1;i++,flag++) {
str += words[i];
// 然后加一个空格组,最后一个不加
if (i == position - 1 && totalWords != 1) continue;
if (flag < rest) {
// 前几个多加一个
for(int j = 0;j < base+1; j++) {
str += " ";
}
} else {
for(int j = 0;j < base; j++) {
str += " ";
}
}
}
result.add(str);
break;
} else if(position == words.length-1 && totalWords != 1) {
String str = "";
// 前几个空字符串需要+1个空格 因为面临空字符串不均匀的问题
for(int i = position-totalWords+1, flag = 0; i <= position;i++,flag++) {
if (i < position) str += words[i] + " ";
else {
str += words[i];
for (int j = 0; j < maxWidth - total; j++) {
str += " ";
}
}
}
// 前几个空字符串需要+1个空格 因为面临空字符串不均匀的问题
position++;
result.add(str);
break;
} else if(position == words.length-1 && totalWords == 1) {
String str = words[words.length-1];
// 全部补全空格
for(int j = 0;j < maxWidth - total; j++) {
str += " ";
}
result.add(str);
position++;
break;
}
position++;
// 应该不存在一个单词比maxWidth还大的情况 有的话看示例怎么处理的
}
}
}
return result;
}
}
leetcode 68题 hard
最新推荐文章于 2024-10-16 10:13:45 发布