A pangram is a string that contains every letter of the English alphabet at least once. For example, "The quick brown fox jumps over the lazy dog" is a pangram because it contains all 26 letters from a to z.
How to Check a Pangram in Java
To determine if a string is a pangram:
- Convert the string to lowercase (to handle case insensitivity).
- Check if all letters from a to z are present in the string.
Examples:
Input: str = "Abcdefghijklmnopqrstuvwxyz"
Output: Yes
Explanation: The given string contains all the letters from a to z (ignoring case).Input: str = "GeeksForGeeks"
Output: No
Explanation: The given string does not contain all the letters from a to z (ignoring case).
Methods to check Pangram String
Method 1: Using Frequency Array
- Convert the string to lowercase.
- Create a boolean array of size 26 to track letters a to z.
- Traverse the string and mark letters as present.
- Check if all letters are marked.
Example:
class GFG {
static int size = 26;
static boolean isLetter(char ch) {
return Character.isLetter(ch);
}
static boolean allLetter(String str, int len) {
str = str.toLowerCase();
boolean[] present = new boolean[size];
for (int i = 0; i < len; i++) {
if (isLetter(str.charAt(i))) {
int index = str.charAt(i) - 'a';
present[index] = true;
}
}
for (int i = 0; i < size; i++) {
if (!present[i])
return false;
}
return true;
}
public static void main(String[] args) {
String str = "Abcdefghijklmnopqrstuvwxyz";
if (allLetter(str, str.length()))
System.out.println("Yes");
else
System.out.println("No");
}
}
Output
Yes
Explanation:
- isLetter() checks whether the current character is an alphabet.
- allLetter() converts the string to lowercase for case-insensitive checking.
- A boolean[] present array stores whether each letter from a to z appears in the string.
- Each character is mapped to an index using ch - 'a' and marked as true.
- The array is checked to ensure no letter is missing.
Method 2: Using Character Traversal
- Convert the string to lowercase.
- Loop from 'a' to 'z'.
- Check if each letter exists in the string using contains().
- If any letter is missing, print No.
Example:
class GFG {
static void allLetter(String str) {
str = str.toLowerCase();
boolean allPresent = true;
for (char ch = 'a'; ch <= 'z'; ch++) {
if (!str.contains(String.valueOf(ch))) {
allPresent = false;
break;
}
}
if (allPresent)
System.out.println("Yes");
else
System.out.println("No");
}
public static void main(String[] args) {
String str = "Abcdefghijklmnopqrstuvwxyz12";
allLetter(str);
}
}
Output
Yes
Explanation:
- The string is converted to lowercase to ignore case differences.
- A boolean variable allPresent assumes all letters are present initially.
- A loop runs from 'a' to 'z' to check every alphabet letter.
- str.contains() checks whether each letter exists in the string.
- If any letter is missing, allPresent is set to false and the loop stops.
- Time Complexity: O(26*N)
- Auxiliary Space: O(1)