package com.算法专练.力扣.重新排列单词间的空格;
import java.util.ArrayList;
import java.util.List;
/**
* @author xnl
* @Description:
* @date: 2022/9/7 22:09
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
String text = " this is a sentence ";
System.out.println(solution.reorderSpaces(text));
}
public String reorderSpaces(String text) {
int space = 0;
List<String> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
int i = 0, j = text.length();
while (i < j){
if (text.charAt(i) == ' '){
space++;
i++;
continue;
}
StringBuilder temp = new StringBuilder();
while (i < j && text.charAt(i) != ' '){
temp.append(text.charAt(i));
i++;
}
list.add(temp.toString());
}
int size = list.size() == 1 ? space : space / (list.size() - 1);
for (String s : list) {
sb.append(s);
for (int k = 0; k < size && space > 0; k++){
sb.append(' ');
space--;
}
}
while (space > 0){
sb.append(' ');
space--;
}
return sb.toString();
}
}
01-14
354
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-09
357
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-13
363
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-23
333
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)