2
public String reorderSpaces(String text) {6
for (char c : text.toCharArray()) {7
if (c == ' ') spaces++;11
String[] words = text.trim().split("\\s+");12
int nWords = words.length;14
StringBuilder sb = new StringBuilder();15
int spacesToApply = 0, extraSpaces = 0;17
// if there is only 1 word, then all spaces will be at the end22
// if there are multiple words, find the spaces to apply between words and also any extra space24
spacesToApply = spaces / (nWords - 1);25
extraSpaces = spaces % (nWords - 1);28
// append every word and then apply spaces29
for (int i = 0; i < words.length - 1; i++) {32
for (int j = 0; j < spacesToApply; j++) sb.append(" ");35
// now append last word separately, bcz we dont want to apply spaces after last word36
sb.append(words[nWords - 1]);38
// if there are any extra spaces that cannot be distributed among words, add them here39
for (int j = 0; j < extraSpaces; j++) sb.append(" ");