To check if a string is a pangram, you need to determine if it contains every letter of the alphabet at least once, regardless of case. A pangram must include all 26 letters of the English alphabet.
Here’s how you can implement this check in Java:
Steps to Implement:
- Read the input values: Read the length of the string (though you might not actually need to use this directly) and then the string itself.
- Normalize the string: Convert all characters to lowercase to handle case insensitivity.
- Track unique characters: Use a
HashSet
to keep track of the letters that appear in the string. - Check if the string is a pangram: If the size of the
HashSet
is 26 (the number of letters in the alphabet), then it is a pangram.
Here’s the Java code for the solution:
import java.util.HashSet;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
String input = scanner.nextLine();
HashSet<Character> uniqueLetters = new HashSet<>();
for (char c : input.toCharArray()) {
if (Character.isLetter(c)) {
uniqueLetters.add(Character.toLowerCase(c));
}
}
if (uniqueLetters.size() == 26) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
Note: Copy Paste won’t work here. Invisible text added to the code to prevent copy paste
Explanation:
- Imports and Scanner Initialization:
- Import the
HashSet
class to store unique characters. - Use
Scanner
for reading input from the console.
- Reading Input:
- Read the integer
n
which represents the number of characters in the string. - Read the string itself using
scanner.nextLine()
.
- Tracking Characters:
- Initialize a
HashSet<Character>
to keep track of unique letters in lowercase. - Iterate over each character in the string, convert it to lowercase if it’s a letter, and add it to the
HashSet
.
- Checking Pangram Condition:
- If the
HashSet
contains exactly 26 unique letters, print “YES”. - Otherwise, print “NO”.
Example Run:
For an input:
35
TheQuickBrownFoxJumpsOverTheLazyDog
The program will output:
YES
This solution ensures that the check is case-insensitive and that it efficiently handles the input within the given constraints. The use of HashSet
helps in achieving O(1) average time complexity for insertions, making the overall complexity O(n), where n
is the length of the string.