2022-06-14 23:33:35 +08:00
# Leetcode Ransom-Note
#### 2022-06-14 13:19
---
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Algorithms:
2022-09-03 15:41:36 +08:00
#algorithm #hash_table
2022-06-14 23:33:35 +08:00
##### Data structures:
2022-09-03 15:41:36 +08:00
#DS #string #array
2022-06-14 23:33:35 +08:00
##### Difficulty:
2022-09-03 15:41:36 +08:00
2022-09-06 20:22:48 +08:00
#leetcode #coding_problem #difficulty_easy
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Related topics:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Links:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
- [Link to problem ](https://leetcode.com/problems/ransom-note/ )
2022-09-03 15:41:36 +08:00
---
2022-06-14 23:33:35 +08:00
### Problem
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
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` .
#### Examples
**Example 1:**
```markdown
**Input:** s = "leetcode"
**Output:** 0
```
**Example 2:**
```markdown
**Input:** s = "loveleetcode"
**Output:** 2
```
**Example 3:**
```markdown
**Input:** s = "aabb"
**Output:** -1
```
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
#### Constraints
**Constraints:**
2022-09-03 15:41:36 +08:00
- `1 <= s.length <= 105`
- `s` consists of only lowercase English letters.
2022-06-14 23:33:35 +08:00
### Thoughts
Super simple hash map, similar to [[Leetcode First-Unique-Character-In-a-String]]
### Solution
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
O(m + n)
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
```cpp
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
// hashmap, O(m + n)
int hashMap[26] = {};
for (char c : magazine) {
hashMap[c - 'a']++;
}
for (char c : ransomNote) {
if (hashMap[c - 'a']-- == 0)
return false;
}
return true;
}
};
2022-09-03 15:41:36 +08:00
```