8000 update · githubcs/Java-Coding-Problems@9ffd2bb · GitHub
[go: up one dir, main page]

Skip to content

Commit 9ffd2bb

Browse files
committed
update
1 parent 507721c commit 9ffd2bb

File tree

1 file changed

+12
-5
lines changed
  • Chapter_01/P05_CountVowelsAndConsonants/src/modern/challenge

1 file changed

+12
-5
lines changed

Chapter_01/P05_CountVowelsAndConsonants/src/modern/challenge/Strings.java

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,22 @@
11
package modern.challenge;
22

3+
import java.util.Arrays;
4+
import java.util.HashSet;
5+
import java.util.Set;
6+
37
public final class Strings {
48

9+
private static final Set<Character> allVowels
10+
= new HashSet(Arrays.asList('a', 'e', 'i', 'o', 'u'));
11+
512
private Strings() {
613
throw new AssertionError("Cannot be instantiated");
714
}
815

916
// Note: For Unicode supplementary characters use codePointAt() instead of charAt()
1017
// 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,
1320
// consider adjust the code accordingly.
1421

1522
public static Pair<Integer, Integer> countVowelsAndConsonantsV1(String str) {
@@ -25,7 +32,7 @@ public static Pair<Integer, Integer> countVowelsAndConsonantsV1(String str) {
2532
int consonants = 0;
2633
for (int i = 0; i < str.length(); i++) {
2734
char ch = str.charAt(i);
28-
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
35+
if (allVowels.contains(ch)) {
2936
vowels++;
3037
} else if ((ch >= 'a' && ch <= 'z')) {
3138
consonants++;
@@ -45,11 +52,11 @@ public static Pair<Long, Long> countVowelsAndConsonantsV2(String str) {
4552
str = str.toLowerCase();
4653

4754
long vowels = str.chars()
48-
.filter(ch -> (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'))
55+
.filter(c -> allVowels.contains((char) c))
4956
.count();
5057

5158
long consonants = str.chars()
52-
.filter(ch -> (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u'))
59+
.filter(c -> !allVowels.contains((char) c))
5360
.filter(ch -> (ch >= 'a' && ch <= 'z'))
5461
.count();
5562

0 commit comments

Comments
 (0)
0