Given string str, the task is to write Java Program check whether the given string is a pangram or not.
A string is a pangram string if it contains all the character of the alphabets ignoring the case of the alphabets.
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).
Method 1 – using a frequency array:
- Convert each letter of the string to the lower or upper case.
- Create a frequency array to mark the frequency of each letter from a to z.
- Then, traverse the frequency array and if there is any letter that is not present in the given string then print No, otherwise print Yes.
Below is the implementation of the above approach:
Java
class GFG {
static int size = 26 ;
static boolean isLetter( char ch)
{
if (!Character.isLetter(ch))
return false ;
return true ;
}
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 letter = str.charAt(i) - 'a' ;
present[letter] = true ;
}
}
for ( int i = 0 ; i < size; i++) {
if (!present[i])
return false ;
}
return true ;
}
public static void main(String args[])
{
String str = "Abcdefghijklmnopqrstuvwxyz" ;
int len = str.length();
if (allLetter(str, len))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Time Complexity: O(N)
Auxiliary Space: O(26)
Method 2 – using Traversal: The idea is to convert the given string into lower case alphabets and then iterate over each character from a to z itself and check if the given string contains all the letters from a to z. If all the letters are present then print Yes, otherwise print No.
Below is the implementation of the above approach:
Java
class GFG {
public static void
allLetter(String str)
{
str = str.toLowerCase();
boolean allLetterPresent = true ;
for ( char ch = 'a' ; ch <= 'z' ; ch++) {
if (!str.contains(String.valueOf(ch))) {
allLetterPresent = false ;
break ;
}
}
if (allLetterPresent)
System.out.println( "Yes" );
else
System.out.println( "No" );
}
public static void main(String args[])
{
String str = "Abcdefghijklmnopqrstuvwxyz12" ;
allLetter(str);
}
}
|
Time Complexity: O(26*N)
Auxiliary Space: O(1)