Skip to content

Instantly share code, notes, and snippets.

@nealhu
Last active August 29, 2015 14:02
Show Gist options
  • Save nealhu/07e151dcbf188516af42 to your computer and use it in GitHub Desktop.
Save nealhu/07e151dcbf188516af42 to your computer and use it in GitHub Desktop.
CC_1_3
// Cracking the Coding Interview
// 1.3 Given two strings, write a method to decide if one is a permutation of the other.
class Permutation {
public static boolean isPermuation(String str1, String str2) {
if (str1 == str2) return true;
if (str1 == null || str2 == null || str1.length() != str2.length()) return false;
int buf[] = new int[256];
int len = str1.length();
for(int i = 0; i< len; i++) {
buf[str1.charAt(i)]++;
}
for(int i = 0; i< len; i++) {
if (--buf[str2.charAt(i)]<0) {
return false;
}
}
for (int i = 0; i< len; i++) {
if (buf[i] != 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
assert isPermuation("","");
assert !isPermuation(null, "a");
assert isPermuation("a", "a");
assert !isPermuation("b", "a");
assert !isPermuation("", "a");
assert isPermuation("abc", "bca");
assert !isPermuation("abcd", "ab");
assert isPermuation(" ", " ");
System.out.println("Tests Passed");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment