Skip to content

Instantly share code, notes, and snippets.

@phillipkent
Last active December 21, 2015 17:18
Show Gist options
  • Save phillipkent/6339154 to your computer and use it in GitHub Desktop.
Save phillipkent/6339154 to your computer and use it in GitHub Desktop.
Anagram Test method in Java. Original question from Gayle Laakmann, "Cracking the Coding Interview", Chapter 1
// Anagram Test: Test if two strings are anagrams of each other
// Original question: Gayle Laakmann, "Cracking the Coding Interview", Chapter 1
//Anagram rules:
// spaces are ignored
// case is ignored
// punctuation is ignored
// letters a..z and digits 0..9 are significant (?)
//Program logic:
//(1) strip punctuation from the strings using regex and convert to lower case
//(2) convert strings to char arrays and test for equality
//Notes:
//(1)
//Proper sorting of unicode strings requires handling of locale for accented characters etc.
//see http://stackoverflow.com/questions/605891/sort-a-single-string-in-java
//(2)
// To capture all punctuation better to use unicode category in the regex, see
// "Regular Expressions Cookbook" page 45
//(3)
//Internet anagram server: http://wordsmith.org/anagram/
import java.util.Arrays;
public class AnagramTest {
public static void main(String[] args) {
String test1 = "I'm an anagram tester";
String test2 = "Transmigrate a Name?";
AnagramTest anag = new AnagramTest();
System.out.print(String.format("Test for anagram equivalence:\n %s \nand:\n %s\nResult:\n",
test1,test2));
System.out.println(anag.test(test1,test2));
}
public boolean test(String s1, String s2) {
// NB this regex does not capture all possible punctuation
char [] c1 = s1.replaceAll("[.,*!?'\" ]", "").toLowerCase().toCharArray();
char [] c2 = s2.replaceAll("[.,*!?'\" ]", "").toLowerCase().toCharArray();
Arrays.sort(c1);
Arrays.sort(c2);
//System.out.println(c1);
//System.out.println(c2);
return Arrays.equals(c1,c2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment