|
| 1 | +package com.baeldung.string; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.Map; |
| 5 | +import java.util.function.Function; |
| 6 | +import java.util.stream.Collectors; |
| 7 | +import java.util.stream.Stream; |
| 8 | + |
| 9 | +public class Pangram { |
| 10 | + private static final int ALPHABET_COUNT = 26; |
| 11 | + |
| 12 | + public static boolean isPangram(String str) { |
| 13 | + if (str == null) |
| 14 | + return false; |
| 15 | + Boolean[] alphabetMarker = new Boolean[ALPHABET_COUNT]; |
| 16 | + Arrays.fill(alphabetMarker, false); |
| 17 | + int alphabetIndex = 0; |
| 18 | + String strUpper = str.toUpperCase(); |
| 19 | + for (int i = 0; i < str.length(); i++) { |
| 20 | + if ('A' <= strUpper.charAt(i) && strUpper.charAt(i) <= 'Z') { |
| 21 | + alphabetIndex = strUpper.charAt(i) - 'A'; |
| 22 | + alphabetMarker[alphabetIndex] = true; |
| 23 | + } |
| 24 | + } |
| 25 | + for (boolean index : alphabetMarker) { |
| 26 | + if (!index) |
| 27 | + return false; |
| 28 | + } |
| 29 | + return true; |
| 30 | + } |
| 31 | + |
| 32 | + public static boolean isPangramWithStreams(String str) { |
| 33 | + if (str == null) |
| 34 | + return false; |
| 35 | + |
| 36 | + // filtered character stream |
| 37 | + String strUpper = str.toUpperCase(); |
| 38 | + Stream<Character> filteredCharStream = strUpper.chars() |
| 39 | + .filter(item -> ((item >= 'A' && item <= 'Z'))) |
| 40 | + .mapToObj(c -> (char) c); |
| 41 | + Map<Character, Boolean> alphabetMap = filteredCharStream.collect(Collectors.toMap(item -> item, k -> Boolean.TRUE, (p1, p2) -> p1)); |
| 42 | + |
| 43 | + return (alphabetMap.size() == ALPHABET_COUNT); |
| 44 | + } |
| 45 | + |
| 46 | + public static boolean isPerfectPangram(String str) { |
| 47 | + if (str == null) |
| 48 | + return false; |
| 49 | + |
| 50 | + // filtered character stream |
| 51 | + String strUpper = str.toUpperCase(); |
| 52 | + Stream<Character> filteredCharStream = strUpper.chars() |
| 53 | + .filter(item -> ((item >= 'A' && item <= 'Z'))) |
| 54 | + .mapToObj(c -> (char) c); |
| 55 | + Map<Character, Long> alphabetFrequencyMap = filteredCharStream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); |
| 56 | + |
| 57 | + return (alphabetFrequencyMap.size() == ALPHABET_COUNT && alphabetFrequencyMap.values() |
| 58 | + .stream() |
| 59 | + .allMatch(item -> item == 1)); |
| 60 | + } |
| 61 | +} |
0 commit comments