Skip to content

Instantly share code, notes, and snippets.

@shehaaz
Last active August 29, 2015 14:16
Show Gist options
  • Save shehaaz/07e8a6ddff05c79b328c to your computer and use it in GitHub Desktop.
Save shehaaz/07e8a6ddff05c79b328c to your computer and use it in GitHub Desktop.
Recursive Anagram Checker in Java
static boolean isAnagram(String s1, String s2)
{
//convert string to lower case
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
if(s1.length() != s2.length())
{
return false;
}
else
{
StringBuilder sb1 = new StringBuilder(s1);
StringBuilder sb2 = new StringBuilder(s2);
return isAnagram(sb1, sb2);
}
}
private static boolean isAnagram(StringBuilder sb1, StringBuilder sb2)
{
if(sb1.length() == 0 && sb2.length() == 0)
{
return true;
}
char checker = sb1.charAt(0);
int index = sb2.indexOf(Character.toString(checker));
//returns -1 if the CharacterSequence is not in StringBuilder
if(index == -1)
{
return false;
}
sb1 = sb1.deleteCharAt(0);
sb2 = sb2.deleteCharAt(index);
return isAnagram(sb1, sb2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment