Repository navigation
Expand file tree
/
Copy pathLeetCode2351.java
More file actions
79 lines (66 loc) · 2.4 KB
/
Copy pathLeetCode2351.java
File metadata and controls
79 lines (66 loc) · 2.4 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
//2351. First Letter to Appear Twice
public class LeetCode2351 {
public char repeatedCharacter_(String s) {
Set<Integer> set = new HashSet<>();
return (char)s.chars()
.filter(ch -> !set.add(ch))
.findFirst()
.orElse('\0');
}
//9ms
public char repeatedCharacter(String s) {
// Just a creative way dont follow blindly
var index = IntStream.range(0, s.length())
.boxed()
.map(i -> s.indexOf(s.charAt(i), i + 1))
.filter( num -> num!=-1)
.min(Comparator.comparingInt(n->n));
return index.map(s::charAt).orElse('\0');
}
//13ms
public char repeatedCharacter1(String s) {
var map = IntStream.range(0, s.length())
.boxed()
.collect(Collectors.groupingBy(s::charAt));
return map.keySet()
.stream()
.filter(k -> map.get(k).size() > 1)
.min(Comparator.comparingInt(k -> map.get(k).get(1)))
.orElse('\0');
}
//Runtime: 11ms
public char repeatedCharacter_1(String s) {
// Just a creative way dont follow blindly
var map = IntStream.range(0, s.length())
.boxed()
.collect(Collectors.groupingBy(i -> s.indexOf(s.charAt(i), i + 1)));
//You can see the distance between same char
//System.out.println(map);
var index = map.keySet()
.stream()
.sorted()
.dropWhile(i -> i == -1)
.findFirst();
//return index.isPresent() ? s.charAt(index.get().intValue()): '0';
return index.map(s::charAt).orElse('\0');
}
//Runtime: 9ms
public char repeatedCharacter_2(String s) {
// Just a creative way dont follow blindly
var set = IntStream.range(0, s.length())
.boxed()
.map(i -> s.indexOf(s.charAt(i), i + 1))
.collect(Collectors.toSet());
var index = set
.stream()
.sorted()
.dropWhile(i -> i == -1)
.findFirst();
//return index.isPresent() ? s.charAt(index.get().intValue()): '0';
return index.map(s::charAt).orElse('0');
}
}