1
1
package modern .challenge ;
2
2
3
+ import java .util .Arrays ;
4
+ import java .util .HashSet ;
5
+ import java .util .Set ;
6
+
3
7
public final class Strings {
4
8
9
+ private static final Set <Character > allVowels
10
+ = new HashSet (Arrays .asList ('a' , 'e' , 'i' , 'o' , 'u' ));
11
+
5
12
private Strings () {
6
13
throw new AssertionError ("Cannot be instantiated" );
7
14
}
8
15
9
16
// Note: For Unicode supplementary characters use codePointAt() instead of charAt()
10
17
// and codePoints() instead of chars()
11
- // Also note that languages can have different number of vowels and consonants
12
- // (e.g., in Roumanian there are 7 vowels: a, e, i, o, u, ă, î (â). Therefore,
18
+ // Also, note that languages can have a different number of vowels and consonants
19
+ // (e.g., in Romanian there are 7 vowels: a, e, i, o, u, ă, î (â). Therefore,
13
20
// consider adjust the code accordingly.
14
21
15
22
public static Pair <Integer , Integer > countVowelsAndConsonantsV1 (String str ) {
@@ -25,7 +32,7 @@ public static Pair<Integer, Integer> countVowelsAndConsonantsV1(String str) {
25
32
int consonants = 0 ;
26
33
for (int i = 0 ; i < str .length (); i ++) {
27
34
char ch = str .charAt (i );
28
- if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ) {
35
+ if (allVowels . contains ( ch ) ) {
29
36
vowels ++;
30
37
} else if ((ch >= 'a' && ch <= 'z' )) {
31
38
consonants ++;
@@ -45,11 +52,11 @@ public static Pair<Long, Long> countVowelsAndConsonantsV2(String str) {
45
52
str = str .toLowerCase ();
46
53
47
54
long vowels = str .chars ()
48
- .filter (ch -> ( ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ))
55
+ .filter (c -> allVowels . contains (( char ) c ))
49
56
.count ();
50
57
51
58
long consonants = str .chars ()
52
- .filter (ch -> ( ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u' ))
59
+ .filter (c -> ! allVowels . contains (( char ) c ))
53
60
.filter (ch -> (ch >= 'a' && ch <= 'z' ))
54
61
.count ();
55
62
0 commit comments