Anagram checking Design an algorithm for checking whether two given words are anagrams, i.e., whether one word can be obtained by permuting the letters of the other. (For example, the words tea and eat are anagrams.)
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
Scanner scanner = new Scanner(System.in);
String str1, str2;
int[] str1LetterCount = new int[26];
int[] str2LetterCount = new int[26];
boolean isAnagram = true;
System.out.print("Enter string 1: ");
str1 = scanner.nextLine();
System.out.print("Enter string 2: ");
str2 = scanner.nextLine();
//Maintain count of all the letters present in first string
for(int i=0; i < str1.length(); i++) {
str1LetterCount[str1.toLowerCase().charAt(i) - 'a']++;
}
//Maintain count of all the letters present in second string
for(int i=0; i < str2.length(); i++) {
str2LetterCount[str2.toLowerCase().charAt(i) - 'a']++;
}
// Check whether each letter count is same in both the strings. If
they
// are equal then the string are anagram otherwise not.
for(int i=0; i < 26; i++) {
if(str1LetterCount[i] != str2LetterCount[i]) {
isAnagram = false;
break;
}
}
if(isAnagram){
System.out.println("Strings are anagram");
}
else {
System.out.println("Strings are not anagram");
}
}
}
Get Answers For Free
Most questions answered within 1 hours.