Skip to content

Commit 3ac506f

Browse files
solves rearange spaces between words
1 parent 17f0d4d commit 3ac506f

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -397,3 +397,4 @@
397397
| 1576 | [Replace All ?'s to Avoid Consecutive Repeating Characters](https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters) | [![Java](assets/java.png)](src/ReplaceAllToAvoidConsecutiveRepeatingCharacters.java) | |
398398
| 1582 | [Special Positions in a Binary Matrix](https://leetcode.com/problems/special-positions-in-a-binary-matrix) | [![Java](assets/java.png)](src/SpecialPositionInABinaryMatrix.java) | |
399399
| 1588 | [Sum of All Odd Length Subarrays](https://leetcode.com/problems/sum-of-all-odd-length-subarrays) | [![Java](assets/java.png)](src/SumOfAllOddLengthSubArrays.java) | |
400+
| 1592 | [Rearrange Spaces Between Words](https://leetcode.com/problems/rearrange-spaces-between-words) | [![Java](assets/java.png)](src/RearrangeSpacesBetweenWords.java) | |

src/RearrangeSpacesBetweenWords.java

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
public class RearrangeSpacesBetweenWords {
5+
public String reorderSpaces(String text) {
6+
final int totalSpaces = countSpaces(text);
7+
final List<StringBuilder> words = getWords(text);
8+
final int spaces = words.size() > 1 ? totalSpaces / (words.size() - 1) : 0;
9+
final int extraSpaces = words.size() > 1 ? totalSpaces % (words.size() - 1) : totalSpaces;
10+
final StringBuilder result = new StringBuilder();
11+
final String spacesAfterWord = " ".repeat(spaces);
12+
for (int i = 0 ; i < words.size() ; i++) {
13+
result.append(words.get(i)).append(i != words.size() -1 ? spacesAfterWord : "");
14+
}
15+
return result.append(" ".repeat(extraSpaces)).toString();
16+
}
17+
18+
private int countSpaces(String s) {
19+
int spaces = 0;
20+
for (int i = 0 ; i < s.length() ; i++) {
21+
if (s.charAt(i) == ' ') spaces++;
22+
}
23+
return spaces;
24+
}
25+
26+
private List<StringBuilder> getWords(String string) {
27+
final List<StringBuilder> words = new ArrayList<>();
28+
StringBuilder word = new StringBuilder();
29+
for (int i = 0 ; i < string.length() ; i++) {
30+
if (string.charAt(i) == ' ') {
31+
if (word.length() > 0) words.add(word);
32+
word = new StringBuilder();
33+
} else {
34+
word.append(string.charAt(i));
35+
}
36+
}
37+
if (word.length() > 0) words.add(word);
38+
return words;
39+
}
40+
}

0 commit comments

Comments
 (0)