Created
April 18, 2012 13:03
-
-
Save zac-xin/2413430 to your computer and use it in GitHub Desktop.
1.4 Write a method to decide if two strings are anagrams or not.
This file contains 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
public class TestAnagram { | |
public static void main(String args[]){ | |
String a = "tomcat as"; | |
String b = " tamcots a"; | |
System.out.println(test(a, b)); | |
} | |
public static boolean test(String s1, String s2){ | |
if(s1.length() != s2.length()) | |
return false; | |
int i; | |
int record[] = new int[255]; | |
int unique = 0; | |
int num_completed = 0; | |
char cs1[] = s1.toCharArray(); | |
for(char c: cs1){ | |
if(record[c] == 0) | |
unique++; | |
record[c]++; | |
} | |
for(i = 0; i < s2.length(); i++){ | |
char t = s2.charAt(i); | |
if(record[t] == 0) | |
return false; | |
record[t]--; | |
if(record[t] == 0){ | |
num_completed++; | |
if(num_completed == unique) | |
//it's a match if s2 has been fully processed | |
return i == s2.length()-1; | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment