-
Notifications
You must be signed in to change notification settings - Fork 25
/
(7 kyu) Reverse words.java
52 lines (43 loc) · 1.21 KB
/
(7 kyu) Reverse words.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// 1 Plain solution
import java.*;
public class Kata {
public static String reverseWords(final String original) {
String[] array = original.split(" ");
if (arr.length == 0) {
return original;
}
List<String> res = new ArrayList<String>();
for (String w : array) {
StringBuilder r = new StringBuilder();
r.append(w);
r = r.reverse();
res.add(r.toString());
}
return String.join(" ", res);
}
}
// 2 Optimized solution
import java.lang.StringBuilder;
public class Kata {
public static String reverseWords(final String original) {
String[] array = original.split(" ");
if (array.length == 0)
return original;
int i = 0;
for(String string : array){
array[i] = new StringBuilder(string).reverse().toString();
i++;
}
return String.join(" ", array);
}
}
// 3 Clever solution
import java.util.Arrays;
import java.util.stream.Collectors;
public class Kata {
public static String reverseWords(final String original) {
return Arrays.stream(original.split("(?<=\\s)|(?=\\s+)"))
.map(str -> new StringBuilder(str).reverse().toString())
.collect(Collectors.joining());
}
}