PangramChecker
A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence “The quick brown fox jumps over the lazy dog” is a pangram, because it uses the letters A-Z at least once (case is irrelevant).Given a string, detect whether or not it is a pangram. Return True if it is, False if not. Ignore numbers and punctuation
Categories:
String.chars() Stream.map() Stream.distinct() Character.isAlphabetic()
Pre-pocess String. Use HashSet remove redundent numbers and non-alpha
public static boolean check(String sentence){
// sort chars in sentences
char[] charArray = sentence.toLowerCase().trim().toCharArray();
Arrays.sort(charArray);
HashSet<Character> set = new HashSet<>();
for (int i = 0; i < charArray.length; i++) {
if(set.contains(charArray[i])){
continue;
}else if(charArray[i] >= 97 && charArray[i] <= 122){
set.add(charArray[i]);
} } System.out.println(set);
return set.size() == 26;
}
That’s not beautiful enough, for removing we can use distinct()
and filter()
public static boolean check(String sentence) {
return sentence.chars().map(Character::toLowerCase).filter(Character::isAlphabetic).distinct().count() == 26;
}
But we can also check if sentence contain all A-Z, with a special for loop
public static boolean check(String sentence) {
sentence = sentence.toLowerCase().trim();
for (char c = 'a'; c < 'z'; c++) {
if (!sentence.contains("" + c)) {
return false;
} } return true;
}
Two solution have same complexity O(n), both are great.