-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRearrangeSpaces.java
More file actions
52 lines (36 loc) · 1.31 KB
/
Copy pathRearrangeSpaces.java
File metadata and controls
52 lines (36 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package LeetcodePractice;
public class RearrangeSpaces {
public static String reorderSpaces(String text) {
int totalSpaces = 0;
for (char c : text.toCharArray()) {
if (c == ' ') totalSpaces++;
}
String[] words = text.trim().split("\\s+");
int numWords = words.length;
if (numWords == 1) {
StringBuilder sb = new StringBuilder(words[0]);
for (int i = 0; i < totalSpaces; i++) {
sb.append(" ");
}
return sb.toString();
}
int spacesBetween = totalSpaces / (numWords - 1);
int extraSpaces = totalSpaces % (numWords - 1);
String spaceStr = " ".repeat(spacesBetween);
StringBuilder result = new StringBuilder();
for (int i = 0; i < numWords; i++) {
result.append(words[i]);
if (i != numWords - 1) {
result.append(spaceStr);
}
}
result.append(" ".repeat(extraSpaces));
return result.toString();
}
public static void main(String[] args) {
String text1 = " this is a sentence ";
System.out.println(reorderSpaces(text1));
String text2 = " practice makes perfect";
System.out.println(reorderSpaces(text2));
}
}