Skip to content

Commit fb4f7d7

Browse files
committed
Add solution for ReverseWordsInAStringIII task
1 parent 93cc7e2 commit fb4f7d7

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package by.andd3dfx.string;
2+
3+
public class ReverseWordsInAStringIII {
4+
5+
public static String reverseWords(String s) {
6+
String[] words = s.split(" ");
7+
for (int i = 0; i < words.length; i++) {
8+
words[i] = reverse(words[i]);
9+
}
10+
return String.join(" ", words);
11+
}
12+
13+
private static String reverse(String word) {
14+
var chars = word.toCharArray();
15+
var n = chars.length;
16+
for (int i = 0; i < n / 2; i++) {
17+
swap(chars, i, n - 1 - i);
18+
}
19+
return new String(chars);
20+
}
21+
22+
private static void swap(char[] chars, int i, int j) {
23+
var tmp = chars[i];
24+
chars[i] = chars[j];
25+
chars[j] = tmp;
26+
}
27+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package by.andd3dfx.string;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import org.junit.Test;
6+
7+
public class ReverseWordsInAStringIIITest {
8+
9+
@Test
10+
public void reverseWords() {
11+
assertThat(ReverseWordsInAStringIII.reverseWords("World"))
12+
.isEqualTo("dlroW");
13+
assertThat(ReverseWordsInAStringIII.reverseWords("a b c"))
14+
.isEqualTo("a b c");
15+
16+
assertThat(ReverseWordsInAStringIII.reverseWords("Let's take LeetCode contest"))
17+
.isEqualTo("s'teL ekat edoCteeL tsetnoc");
18+
assertThat(ReverseWordsInAStringIII.reverseWords("Mr Ding"))
19+
.isEqualTo("rM gniD");
20+
}
21+
}

0 commit comments

Comments
 (0)