Leetcode / 383. Ransom Note
Pick a programming language:
Here is the source code for the solution to this problem.
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
for (int i = 0; i < magazine.length(); i++) {
char c = magazine.charAt(i);
if (hashMap.containsKey(c)) {
hashMap.put(c, hashMap.get(c) + 1);
}
else {
hashMap.put(c, 1);
}
}
for (int i = 0; i < ransomNote.length(); i++) {
char c = ransomNote.charAt(i);
if (!hashMap.containsKey(c)) {
return false;
}
else {
int newCount = hashMap.get(c) - 1;
if (newCount < 0) {
return false;
}
hashMap.put(c, newCount);
}
}
return true;
}
}
Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: