import java.io.*; class CheckAnagram { boolean anagram(String a, String b) { if (a.length() != b.length()) return false; int[] alpha= new int[256]; int chars = 0; int num = 0; char[] a_array = a.toCharArray(); for (char c : a_array) { if (alpha[c] == 0) ++chars; ++alpha[c]; } for (int i = 0; i < b.length(); ++i) { int c = (int) b.charAt(i); if (alpha[c] == 0) { return false; } --alpha[c]; if (alpha[c] == 0) { ++num; if (num == chars) { return i == b.length() - 1; } } } return false; } } class AnagramFinder { public static void main (String[] args) { CheckAnagram c=new CheckAnagram(); System.out.println ("Enter the first string"); String str1 = ""; String str2 = ""; InputStreamReader input1 = new InputStreamReader(System.in); BufferedReader r1 = new BufferedReader(input1); try { str1 = r1.readLine(); System.out.println ("Enter the second string"); str2 = r1.readLine(); } catch(Exception e){} boolean value =c. anagram(str1,str2); if(value == true) System.out.println("The string are anagrams."); else System.out.println("The string are NOT anagrams. "); } }
Output: |
---|
Enter the first string |
angrama |
Enter the second string |
amagran |
The string are anagrams of each other |