https://leetcode.cn/problems/rearrange-spaces-between-words/
class Solution {
public String reorderSpaces(String text) {
//识别出空格和单词的数量
//" this is a sentence "
int spaceNum = 0;
//单词list
List<String> strList = new ArrayList<>();
//每个单词
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0, len = text.length(); i < len; i++) {
char oneChar = text.charAt(i);
if (oneChar == ' ') {
//遇到空格
stringBuilder = getStringBuilder(strList, stringBuilder);
//没存过
spaceNum++;
} else {
//不是空格,直接加起来
stringBuilder.append(oneChar);
}
}
if (stringBuilder.length() > 0) {
strList.add(stringBuilder.toString());
}
//计算每个字符间要放多少个空格
// 空格/(单词-1)
//间隔空格数
int splictNum;
//末尾空格数
int endNum;
if (strList.size() == 1) {
splictNum = 0;
endNum = spaceNum;
} else {
//间隔空格数
splictNum = spaceNum / (strList.size() - 1);
//末尾空格数
endNum = spaceNum % (strList.size() - 1);
}
StringBuilder stringBuilder1 = new StringBuilder();
for (int i = 0, len = strList.size(); i < len; i++) {
stringBuilder1.append(strList.get(i));
if (i == len - 1) {
break;
}
extracted(splictNum, stringBuilder1);
}
extracted(endNum, stringBuilder1);
return stringBuilder1.toString();
}
private void extracted(int splictNum, StringBuilder stringBuilder1) {
for (int j = 0; j < splictNum; j++) {
stringBuilder1.append(" ");
}
}
private StringBuilder getStringBuilder(List<String> strList, StringBuilder stringBuilder) {
//遇到空格
if (stringBuilder.length() > 0) {
//存过
strList.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
}
return stringBuilder;
}
}