Programming Examples
Java program to check whether the two strings anagram of each other or not
Anagram :- When two strings contain the same characters irrespective of the order of occurrence then such strings are known as Anagram.
For Example :-
String1 = LISTEN
String2 = SILENT
So as we can see that both strings have same characters, only the order of characters is different so this is an Anagram.
Solution
import java.io.*;
import java.util.Arrays;
import java.util.Collections;
class LFC {
static boolean anagram(char[] str1, char[] str2)
{
// Get lenghts of both strings
int len1 = str1.length;
int len2 = str2.length;
// If length of both strings is not same,
// then they cannot be anagram
if (len1 != len2)
return false;
// Sort both strings
Arrays.sort(str1);
Arrays.sort(str2);
// Compare sorted strings
for (int i = 0; i < len1; i++)
if (str1[i] != str2[i])
return false;
return true;
}
/* Driver program to test to print printDups*/
public static void main(String args[])
{
char str1[] = { 'l', 'i', 's', 't', 'e', 'n' };
char str2[] = { 's', 'i', 'l', 'e', 'n', 't' };
if (anagram(str1, str2))
System.out.println("The two strings are"
+ " anagram of each other");
else
System.out.println("The two strings are not"
+ " anagram of each other");
}
}
Output
The two strings are anagram of each other