Skip to content

Instantly share code, notes, and snippets.

@UncleGarden
Last active August 29, 2015 14:02
Show Gist options
  • Save UncleGarden/ee937ea3ffcebad6264f to your computer and use it in GitHub Desktop.
Save UncleGarden/ee937ea3ffcebad6264f to your computer and use it in GitHub Desktop.
CareerCup 150
/**
* 1.3 Given two strings, write a method to decide if one is a permutation of
* the other.
*
* @author Jiateng
*/
public class CC1_3 {
//Time O(n), Space O(1)
public static boolean permutation(String s1, String s2) {
//null should be check first
if (s1 == null || s2 == null) {
return false;
}
if (s1.isEmpty() && s2.isEmpty()) {
return true;
}
if (s1.isEmpty() || s2.isEmpty()) {
return false;
}
if (s1.length() != s2.length()) {
return false;
}
int[] array = new int[256];
//char to int, ASCII
for (char c : s1.toCharArray()) {
//System.out.println(c);
//System.out.println(Integer.valueOf(c));
array[c] += 1;
}
//if s1 is equal to s2, all in array will be 0
for (char c : s2.toCharArray()) {
array[c] -= 1;
}
for (int i : array) {
if (i != 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(permutation("", ""));
System.out.println(permutation("abc", "cba"));
System.out.println(permutation("asf", ""));
System.out.println(permutation(null, "asf"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment