출처: leetcode
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraints:
- 1 <= ransomNote.length, magazine.length <= 105
- ransomNote and magazine consist of lowercase English letters.
내솔루션. 실제 답지는 왜이리 복잡하게 했는지
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> ransom_hash;
unordered_map<char, int> magazine_hash;
for(char &i : ransomNote){
ransom_hash[i]++;
}
for(char &i : magazine){
magazine_hash[i]++;
}
for(auto &[key,val]: ransom_hash){ // find the other hash's key.
if(magazine_hash.find(key) !=magazine_hash.end() ){
magazine_hash[key] -= ransom_hash[key];
}
else{
return false;
}
}
for(auto &[key,val] : magazine_hash){
if(val < 0){
return false;
}
}
return true;
}
};
'Data Structure & Algorithms > Hasing' 카테고리의 다른 글
[Hashing] 2260. Minimum Consecutive Cards to Pick Up (0) | 2023.03.17 |
---|---|
[Hashing] 해쉬를 핵심만 정리해보자 (0) | 2023.03.12 |
[Hashing] Find Players With Zero or One Losses (0) | 2023.01.06 |
[Hashing] Largest Unique Number (0) | 2023.01.04 |
[Hashing] Maximum Number of Balloons (0) | 2023.01.03 |
댓글