[LeetCode] Ransom Note

383. Ransom Note

Given two strings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int arr[26]{0};
for(auto ch : magazine) ++arr[ch-'a'];
for(auto ch : ransomNote) --arr[ch-'a'];
for(int i = 0; i < 26; i++) {
if(arr[i] < 0) return false;
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/14/PS/LeetCode/ransom-note/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.