-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy path(7 kyu) Remove duplicate words.java
54 lines (44 loc) · 1.16 KB
/
(7 kyu) Remove duplicate 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
53
54
// 1 Plain solution
import java.util.*;
class Solution {
public static String removeDuplicateWords(String s) {
String[] words = s.split(" ");
List<String> uniqueWords = new ArrayList<String>();
for (String word : words) {
if (!uniqueWords.contains(word)) {
uniqueWords.add(word);
}
}
return String.join(" ", uniqueWords);
}
}
// 2 Straightforward solution
class Solution {
public static String removeDuplicateWords(String s) {
StringBuilder res = new StringBuilder();
for(String word : s.split(" ")) {
if (!res.toString().contains(word)) {
res.append(word).append(" ");
}
}
return res.toString().trim();
}
}
// 3 Clever solution
import java.util.*;
import java.util.stream.*;
class Solution {
public static String removeDuplicateWords(String s){
return Arrays
.stream(s.split("\\s+"))
.distinct()
.collect(Collectors.joining(" "));
}
}
// 4 Coding golf
import java.util.*;
public class Solution {
public static String removeDuplicateWords(String s) {
return String.join(" ", new LinkedHashSet<>(Arrays.asList(s.split(" "))));
}
}