Skip to content

Instantly share code, notes, and snippets.

@dineshappavoo
Last active August 29, 2015 14:00
Show Gist options
  • Save dineshappavoo/11207936 to your computer and use it in GitHub Desktop.
Save dineshappavoo/11207936 to your computer and use it in GitHub Desktop.
Find whether two strings are anagrams
public boolean isAnagram(String str1, String str2)
{
//To get the no of occurrences of each character and store it in their ASCII location
int[] strCountArr1=getASCIICountArr(str1);
int[] strCountArr2=getASCIICountArr(str2);
//To Test whether the two arrays have the same count of characters. Array size 256 since ASCII 256 unique values
for(int i=0;i<256;i++)
{
if(strCountArr1[i]!=strCountArr2[i])
return false;
}
return true;
}
public int[] getASCIICountArr(String str)
{
char c;
//Array size 256 for ASCII
int[] strCountArr=new int[256];
for(int i=0;i<str.length();i++)
{
c=str.charAt(i);
c=Character.toUpperCase(c);// If both the cases are considered to be the same
strCountArr[(int)c]++; //To increment the count in the character's ASCII location
}
return strCountArr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment