Skip to content

Instantly share code, notes, and snippets.

@michaelniu
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelniu/52defe4d1bb7b373b00d to your computer and use it in GitHub Desktop.
Save michaelniu/52defe4d1bb7b373b00d to your computer and use it in GitHub Desktop.
cc150-1.3
/*
* 1.3 Given two strings, write a method to decide if one is a permutation
* of the other.
create a hashtable <Integer,Integer> Key is the char of the
* String element, value is the count of char in the string travese first
* string to initial the hashtable. use the hashtable to compare the second
* string chars if any value become 0 return false finally return true;
*
* O(n) with space o(n)
*/
public static void main(String[] args) {
// string no same size
String str1 = "abcdfs";
String str2 = "cba";
System.out.println(isPermutation(str1, str2));
// String same size but not permutaion
str1 = "fasfasfsahf;uip";
str2 = "fasfasfsahfauip";
System.out.println(isPermutation(str1, str2));
// two null String
str1 = null;
str2 = null;
System.out.println(isPermutation(str1, str2));
// two empty String
str1 = "";
str2 = "";
System.out.println(isPermutation(str1, str2));
// two permutaion String
str1 = "asdfghjkl;l";
str2 = "asdfghjkl;l";
System.out.println(isPermutation(str1, str2));
}
private static boolean isPermutation(String str1, String str2) {
Hashtable charTable = new Hashtable();
if (str1 == null && str2 == null)
return false;
if (str1 == null || str2 == null)
return false;
if (str1.length() != str2.length())
return false;
if (str1.length() == str2.length() && str1.length() <= 1)
return false;
for (int i = 0; i < str1.length(); i++) {
if (charTable.get(str1.charAt(i)) != null) {
int temp = (int) charTable.get(str1.charAt(i));
charTable.put(str1.charAt(i), (temp + 1));
} else {
charTable.put(str1.charAt(i), 1);
}
}
for (int j = 0; j < str2.length(); j++) {
if (charTable.get(str2.charAt(j)) != null) {
int current = (int) charTable.get(str2.charAt(j));
if (current > 0) {
charTable.put((str2.charAt(j)), current - 1);
} else
return false;
} else
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment