forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrings.java
More file actions
91 lines (66 loc) · 2.65 KB
/
Copy pathStrings.java
File metadata and controls
91 lines (66 loc) · 2.65 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
80
81
82
83
84
85
86
87
88
89
90
91
package modern.challenge;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public final class Strings {
private Strings() {
throw new AssertionError("Cannot be instantiated");
}
public static Map<Character, Integer> countDuplicateCharactersV1(String str) {
if (str == null || str.isBlank()) {
// or throw IllegalArgumentException
return Collections.emptyMap();
}
Map<Character, Integer> result = new HashMap<>();
// or use for(char ch: str.toCharArray()) { ... }
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
result.compute(ch, (k, v) -> (v == null) ? 1 : ++v);
}
return result;
}
public static Map<String, Integer> countDuplicateCharactersVCP1(String str) {
if (str == null || str.isEmpty()) {
// or throw IllegalArgumentException
return Collections.emptyMap();
}
Map<String, Integer> result = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
/*
String ch = String.valueOf(Character.toChars(str.codePointAt(i)));
if (i < str.length() - 1 && str.codePointCount(i, i + 2) == 1) {
i++;
}
*/
// or, like this (this code produce the same result as the commented code above
int cp = str.codePointAt(i);
String ch = String.valueOf(Character.toChars(cp));
if(Character.charCount(cp) == 2) { // 2 means a surrogate pair
i++;
}
result.compute(ch, (k, v) -> (v == null) ? 1 : ++v);
}
return result;
}
public static Map<Character, Long> countDuplicateCharactersV2(String str) {
if (str == null || str.isBlank()) {
// or throw IllegalArgumentException
return Collections.emptyMap();
}
Map<Character, Long> result = str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
return result;
}
public static Map<String, Long> countDuplicateCharactersVCP2(String str) {
if (str == null || str.isBlank()) {
// or throw IllegalArgumentException
return Collections.emptyMap();
}
Map<String, Long> result = str.codePoints()
.mapToObj(c -> String.valueOf(Character.toChars(c)))
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
return result;
}
}