Skip to content

Commit c7b5adc

Browse files
committed
code refactor
1 parent b38b347 commit c7b5adc

File tree

2 files changed

+8
-39
lines changed

2 files changed

+8
-39
lines changed
Lines changed: 7 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.thealgorithms.strings;
22

3+
import java.util.Arrays;
4+
import java.util.Collections;
5+
36
/**
47
* Given an input string s, reverse the order of the words.
58
* A word is defined as a sequence of non-space characters.
@@ -14,43 +17,9 @@ public final class ReverseWordsInString {
1417
private ReverseWordsInString() {
1518
}
1619

17-
public static String reverseWordsInString(String s) {
18-
19-
s = s.replaceAll("\\s+", " ").trim();
20-
StringBuilder res = new StringBuilder();
21-
int start = 0;
22-
int end = 0;
23-
24-
while (start < s.length()) {
25-
26-
Integer[] arr = findNextWord(s, start, end);
27-
start = arr[0];
28-
end = arr[1];
29-
30-
String word = s.substring(start, end);
31-
32-
start = end;
33-
34-
if (res.length() > 0) {
35-
res.insert(0, " ");
36-
res.insert(0, word);
37-
} else {
38-
res.append(word);
39-
}
40-
}
41-
return res.toString();
42-
}
43-
44-
private static Integer[] findNextWord(String s, int start, int end) {
45-
while (s.charAt(start) == ' ') {
46-
start++;
47-
}
48-
end = start + 1;
49-
50-
while (end < s.length() && (s.charAt(end) != ' ')) {
51-
end++;
52-
}
53-
54-
return new Integer[] {start, end};
20+
public static String reverseWordsInString(final String s) {
21+
var words = s.trim().split("\\s+");
22+
Collections.reverse(Arrays.asList(words));
23+
return String.join(" ", words);
5524
}
5625
}

src/test/java/com/thealgorithms/strings/ReverseWordInStringTest.java renamed to src/test/java/com/thealgorithms/strings/ReverseWordsInStringTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import org.junit.jupiter.api.Test;
66

7-
public class ReverseWordInStringTest {
7+
public class ReverseWordsInStringTest {
88

99
@Test
1010
public void testCorrectReverseWordsInTheString() {

0 commit comments

Comments
 (0)