forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1592.java
38 lines (37 loc) · 1.28 KB
/
_1592.java
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
package com.fishercoder.solutions;
public class _1592 {
public static class Solution1 {
public String reorderSpaces(String text) {
int spaceCount = 0;
for (char c : text.toCharArray()) {
if (c == ' ') {
spaceCount++;
}
}
String[] words = text.trim().split("\\s+");
if (words.length == 1) {
StringBuilder sb = new StringBuilder(words[0]);
for (int i = 0; i < spaceCount; i++) {
sb.append(" ");
}
return sb.toString();
}
int trailingSpaces = spaceCount % (words.length - 1);
int newSpaces = spaceCount / (words.length - 1);
StringBuilder sb = new StringBuilder();
for (int j = 0; j < words.length; j++) {
sb.append(words[j]);
if (j < words.length - 1) {
for (int i = 0; i < newSpaces; i++) {
sb.append(" ");
}
} else {
for (int i = 0; i < trailingSpaces; i++) {
sb.append(" ");
}
}
}
return sb.toString();
}
}
}