题目给定字符串text,按照空格分割,得到单词集合,并统计空格数。
class Solution:
def reorderSpaces(self, text: str) -> str:
words = text.split()
space = text.count(' ')
if len(words) == 1:
return words[0] + ' ' * space
per_space, rest_space = divmod(space, len(words) - 1)
return (' ' * per_space).join(words) + ' ' * rest_space
class Solution {
public String reorderSpaces(String text) {
int length = text.length();
String[] words = text.trim().split("\\s+");
int space = length;
for (String word : words) {
space -= word.length();
}
StringBuilder sb = new StringBuilder();
if (words.length == 1) {
sb.append(words[0]);
for (int i = 0; i < space; i++) {
sb.append(' ');
}
return sb.toString();
}
int perSpace = space / (words.length - 1);
int restSpace = space % (words.length - 1);
for (int i = 0; i < words.length; i++) {
if (i > 0) {
for (int j = 0; j < perSpace; j++) {
sb.append(' ');
}
}
sb.append(words[i]);
}
for (int i = 0; i < restSpace; i++) {
sb.append(' ');
}
return sb.toString();
}
}