Created
October 18, 2011 17:58
-
-
Save ox/1296145 to your computer and use it in GitHub Desktop.
See if 2 words are anagrams
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// compile it with: | |
// javac Anagram.java | |
// run it with: | |
// java Anagram word1 word2 | |
// where word1 and word2 are words of your choosing | |
public class Anagram { | |
public static boolean is_anagram(String a, String b) { | |
System.out.println("a: " + a + ", b: " + b ); | |
//if a == b or if their lengths are 0 then we are done and can return true | |
if(a == b || a.length() == 0 && a.length() == 0) | |
return true; | |
//k is the last index of the first character of a | |
int k = b.lastIndexOf(a.charAt(0)); | |
//#lastIndexOf returns -1 if there is no index for the letter we want to find | |
//if k != -1 then we make #is_anagram check all the letters after the first (substring(1)) | |
// and the 2nd word minus the k-th letter (the letter that matches the first letter of a). | |
// to do that we take all the letters before k (substring(0,k)) and add it to the letters | |
// after k to the end of the string (substring(k+1)) | |
if(k != -1) | |
return is_anagram(a.substring(1), b.substring(0,k) + b.substring(k+1)); | |
// if k is in fact -1 then these words are not anagrams and we send back false | |
else | |
return false; | |
} | |
public static void main(String[] args) { | |
if(is_anagram(args[0], args[1])) | |
System.out.println("true"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment