LeetCode #2
I’ve started doing LeetCode. Of course, it’s free plan but, if I get interest I will buy the premium version. Today is the first time so I am doing Explore. I am writing blog simultaniously like in “The Social Network”.
What I’ve Learned (After today’s problems)
First, hashmap. Actually, I just don’t get it.
Disclaimer
My LeetCode is free plan. I am posting just the free algorithms for now on. Also, I am using JAVA to code.
383. Ransom Note
Solution
So, Hashmap approach. This question is about hashmap. Splitting all the char values in String and finding if it matches or not. It’s simple when we use array or list but takes a long time.
Here, we are using hashmap. For each characters on the String, we can count how many characters were found. We can check if magazine
is including each characters.
import java.util.HashMap;
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
HashMap<Character, Integer> magazineLetters = new HashMap<>();
for(int i = 0; i<magazine.length(); i++) {
char m = magazine.charAt(i);
int currentCount = magazineLetters.getOrDefault(m,0);
magazineLetters.put(m, currentCount + 1);
}
for(int i = 0; i<ransomNote.length(); i++) {
char r = ransomNote.charAt(i);
int currentCount = magazineLetters.getOrDefault(r,0);
if(currentCount == 0) {
return false;
}
magazineLetters.put(r, currentCount - 1);
}
return true;
}
}
Hashmap saves Key and Value in pair. Hashmap has a advantage of fast searching. getOrDefault()
is for retrieving value rather than null.
We can set by getOrDefault(r,0)
then null value is retrived as zero. It’s not easy. I need to review the hashmap and other sort of things in java.