I was reading a coding book, trying to learn more about Java, and came across this problem.
The question asks: "Given two strings, write a method to decide if one is a permutation of the other."
After mulling it over for a minute or so, I decided to go with a Hashmap solution. My logic was that add, remove, and search were all O(1), so that it'd be a fast solution. My code is as follows:
public static boolean isPermutation(String a, String b) {
if(a.length() != b.length()) {
return false;
}
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for(int x = 0; x < a.length(); x++) {
char letter = a.charAt(x);
if(!(map.containsKey(letter))) {
map.put(letter, 1);
}
else {
int val = map.get(letter) + 1;
map.put(letter, val);
}
}
for(int y = 0; y < b.length(); y++) {
char letter = b.charAt(y);
if(!(map.containsKey(letter))) {
return false;
}
else {
int val = map.remove(letter) - 1;
if(val > 0) {
map.put(letter, val);
}
}
}
return true;
}
The book, however, uses an array as its answer.
public boolean permutation(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] letters = new int[256];
char[] s_array = s.toCharArray();
for (char c : s_array) {
letters[c]++;
}
for (int i = 0; i < t.length(); i++) {
int c = (int) t.charAt(i);
if (--letters[c] < e) {
return false;
}
}
return true;
}
I have three questions.
First, I'd like to know whether my implementation is less efficient than the book's - and if so, what the inefficiencies are, and whether they can be corrected so that the Hashmap implementation is better (or at least equal) to the given array implementation.
Second, I understand that my Hashmap uses autoboxing to convert from Character to char. Is there a significant slowdown that comes with autoboxing?
And third, in my code I tried to avoid using the Hashmap's remove() function. My logic was that, while it should theoretically be O(1) to remove, using put() to instead replace the existing key with a new one (in this case, overwriting the old value) would be more efficient, since replacing would be less costly than removing, and then adding. Is my logic correct? Is it something that I should be doing?
Thank you very much!