1
class Solution {
2
public String reorderSpaces(String text) {
3
int spaces = 0;
4

5
// count the spacex
6
for (char c : text.toCharArray()) {
7
if (c == ' ') spaces++;
8
}
9

10
// form word array
11
String[] words = text.trim().split("\\s+");
12
int nWords = words.length;
13

14
StringBuilder sb = new StringBuilder();
15
int spacesToApply = 0, extraSpaces = 0;
16

17
// if there is only 1 word, then all spaces will be at the end
18
if (nWords == 1) {
19
extraSpaces = spaces;
20
}
21

22
// if there are multiple words, find the spaces to apply between words and also any extra space
23
else {
24
spacesToApply = spaces / (nWords - 1);
25
extraSpaces = spaces % (nWords - 1);
26
}
27

28
// append every word and then apply spaces
29
for (int i = 0; i < words.length - 1; i++) {
30
sb.append(words[i]);
31

32
for (int j = 0; j < spacesToApply; j++) sb.append(" ");
33
}
34

35
// now append last word separately, bcz we dont want to apply spaces after last word
36
sb.append(words[nWords - 1]);
37

38
// if there are any extra spaces that cannot be distributed among words, add them here
39
for (int j = 0; j < extraSpaces; j++) sb.append(" ");
40

41
return sb.toString();
42
}
43
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0