1.

Check if two strings are anagrams of each other in Java

Answer»

An anagram of a STRING is a string that has the same characters with the same frequency. Only the character order can be different. An EXAMPLE of a anagram is given as follows:

String = silent Anagram = listen

A program that checks if two strings are anagrams of each other in Java is given as follows:

import java.io.*; import java.util.*; public class Demo {    STATIC boolean checkAnagram(char s1[], char s2[])    {        int alphaCount1[] = NEW int [256];        Arrays.fill(alphaCount1, 0);        int alphaCount2[] = new int [256];        Arrays.fill(alphaCount2, 0);        int i;        for (i = 0; i <s1.length && i < s2.length ; i++)        {            alphaCount1[s1[i]]++;            alphaCount2[s2[i]]++;        }        if (s1.length != s2.length)            return false;        for (i = 0; i < 256; i++)        {            if (alphaCount1[i] != alphaCount2[i])                return false;        }        return true;    }    public static void main(String args[])    {        String str1 = "triangle";        String str2 = "integral";        char s1[] = str1.toCharArray();        char s2[] = str2.toCharArray();        System.out.println("String 1: " + str1 );        System.out.println("String 2: " + str2 );        if ( checkAnagram(s1, s2) )            System.out.println("The two strings are anagram of each other");        else            System.out.println("The two strings are not anagram of each other");    } }

The output of the above program is as follows:

String 1: triangle String 2: integral The two strings are anagram of each other


Discussion

No Comment Found