I am working on a solution to a very common Java problem involving Strings. I would like to write a method to see if a string is a permutation (anagram) of another.
My solution is this: I am writing a method that takes two Strings. I iterate through one String and put the characters that are found into a HashMap, where the key is the letter, and the value is the number of occurrences of that letter, as an int. Once I finish iterating through the first String, I iterate through the second String and decrement the values of each character found in the same HashMap.
Once a key reaches zero, I remove the key/value pair altogether from the HashMap. Once I finish iterating through the second String, I then merely check to see if the HashMap is empty. If it is, then the two Strings are permutations/anagrams of one another, otherwise the method returns false.
My method is as follows:
public boolean checkPermutation (String stringA, String stringB) {
if (stringA.length() != stringB.length()) {
return false;
}
else {
HashMap alpha = new HashMap();
for (int i = 0; i < stringA.length(); i++) {
if (!alpha.containsKey(stringA.charAt(i))) {
alpha.put(stringA.charAt(i), 0);
}
else {
Integer value = (Integer) alpha.get(stringA.charAt(i));
int newValue = value.intValue();
alpha.put(stringA.charAt(i), newValue++);
}
}
for (int j = 0; j < stringB.length(); j++) {
if (alpha.containsKey(stringB.charAt(j))) {
Integer value = (Integer) alpha.get(stringA.charAt(j));
int newValue = value.intValue();//null pointer exception here
if (newValue > 1) {
alpha.put(stringB.charAt(j), newValue--);
}
else {
alpha.remove(stringB.charAt(j));
}
}
}
if (alpha.isEmpty())
return true;
else
return false;
}
}
My problem is that my solution is case-sensitive (i.e. If I enter “Hello”, and “oellH”, I get a null pointer exception). I would like to make this solution case-insensitive, and figure out why I am getting a Null-Pointer Exception. Can anyone see what I am doing wrong?
As a minor follow up question, is such a solution of type O(n) despite there being two for-loops?
Try changing stringA to stringB.
Because if you give different String which dont have same characters in it the value will be null and it will through NPE.
Change both string to lowercase or uppercase.