Hi all,
I'm just now starting down the journey down the Leetcode grind. I'm having a hard time understanding why my code isn't working for Leetcode 242 - Valid Anagram. My solution is in Java.
My algorithm is as follows:
If the two strings aren't of the same length, return false. Can't be a valid anagram since a valid anagram needs to be the same length for both Strings.
Once it's confirmed both Strings are of the same length, create two HashMaps to count the frequency of each letter in each respective String. (This is done using the first two for-loops in the code below).
Once the two hashmaps are created, loop through the keys of sHashMap, and compare the values from sHashMap to the values in tHashMap for the same key to check of the value associated with each key is the same. For example, compare the value of key 'a' in each HashMap. If the values are not equal, the anagram is not valid.
Before starting the last loop through, I have an if-condition checking if tHashMap has all the values in sHashMap. If it doesn't, insert a dummy key with an associated value of 0.
This algorithm works for the example test cases but Leetcode says my code it wrong. No error thrown, just wrong answer.
Any help is appreciated.
Thanks!
EDIT: Formatting, Haven't posted code to Reddit before this.
class Solution {
public boolean isAnagram(String s, String t) {
HashMap<Character, Integer> sHashMap = new HashMap<Character, Integer>();
HashMap<Character, Integer> tHashMap = new HashMap<Character, Integer>();
if(s.length() != t.length()) {
return false;
}
for(int i = 0; i < s.length(); i ) {
char sCurrentChar = s.charAt(i);
if(sHashMap.containsKey(sCurrentChar)){
int sOldCounter = sHashMap.get(sCurrentChar);
int sNewCounter = sOldCounter 1;
sHashMap.put(sCurrentChar, sNewCounter);
} else {
sHashMap.put(sCurrentChar, 1);
}
}
for(int j = 0; j < t.length(); j ) {
char tCurrentChar = t.charAt(j);
if(tHashMap.containsKey(tCurrentChar)) {
int tOldCounter = tHashMap.get(tCurrentChar);
int tNewCounter = tOldCounter 1;
tHashMap.put(tCurrentChar, tNewCounter);
} else {
tHashMap.put(tCurrentChar, 1);
}
}
for(Character key : sHashMap.keySet()) {
if(!(tHashMap.containsKey(key))) {
tHashMap.put(key, 0);
}
if(sHashMap.get(key) != tHashMap.get(key)) {
return false;
}
}
return true;
}
}
Subreddit
Post Details
- Posted
- 2 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/leetcode/co...