class Solution {
public String reorderSpaces(String text) {
int numLetters = 0;
List<String> words = new LinkedList<>();
String word = "";
for (int i = 0; i < text.length(); i++) {
if (Character.isLetter(text.charAt(i))) word += text.charAt(i);
else if (word.equals("") == false) {
numLetters = word.length();
words.add(word);
word = "";
}
}
if (word.equals("") == false) {
numLetters += word.length();
words.add(word);
}
if (words.size() == 1) {
return words.get(0) + " ".repeat(text.length() - numLetters);
}
String ans = "";
for (int i = 0; i < words.size(); i++) {
ans += words.get(i);
ans += i < words.size() - 1 ? " ".repeat((text.length() - numLetters) / (words.size() - 1)) : " ".repeat((text.length() - numLetters) % (words.size() - 1));
}
return ans;
}
}