🌕 68. 文本左右对齐
2022年10月10日
- algorithm
🌕 68. 文本左右对齐
难度: 🌕
问题描述
解法
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
// 思路:
// 依次放入每行的单词,单词间至少一个空格隔开
int len = words.length;
List<String> res = new ArrayList<>();
List<String> list = new ArrayList<>();
int preWord = 0; // 仅单词长度
int preLen = 0; // 单词 + 空格长度
int i = 0;
while(i < len) {
String cur = words[i];
if(preLen + cur.length() <= maxWidth) {
list.add(cur);
preWord += cur.length();
preLen += cur.length() + 1;
} else {
// print(list);
// System.out.println(preWord);
res.add(getStr(list, maxWidth, preWord));
list = new ArrayList<>();
list.add(cur);
preWord = cur.length();
preLen = cur.length() + 1;
}
i ++;
}
res.add(getLeft(list, maxWidth));
return res;
}
private void print(List<String> list) {
System.out.println();
for(String str: list) {
System.out.print(str + " ");
}
}
private String getLeft(List<String> list, int maxWidth) {
StringBuilder sb = new StringBuilder();
int len = list.size();
for(int i = 0; i < len - 1; i ++) {
sb.append(list.get(i)).append(' ');
}
sb.append(list.get(len - 1));
int left = maxWidth - sb.length();
sb.append(getSpace(left));
return sb.toString();
}
private String getStr(List<String> list, int maxWidth, int preWord) {
StringBuilder sb = new StringBuilder();
int len = list.size();
int space = maxWidth - preWord; // 总空格数
if(len == 1) {
sb.append(list.get(0));
sb.append(getSpace(space));
return sb.toString();
}
int avg = space / (len - 1); // 每个单词分配的空格数
int left = space % (len - 1); // 左侧有 left 个空格数要多一个
sb.append(list.get(0));
for(int i = 0; i < left; i ++) {
sb.append(getSpace(avg + 1));
sb.append(list.get(i + 1));
}
for(int i = left; i < len - 1; i ++) {
sb.append(getSpace(avg));
sb.append(list.get(i + 1));
}
// sb.append(list.get(len - 1));
return sb.toString();
}
private String getSpace(int n) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n; i ++) {
sb.append(' ');
}
return sb.toString();
}
}