跳到主要内容

383.赎金信

链接:383.赎金信
难度:Easy
标签:哈希表、字符串、计数
简介:给你一个赎金信 (ransomNote) 字符串和一个杂志(magazine)字符串,判断 ransomNote 能不能由 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false 。

题解 1 - typescript

  • 编辑时间:2021-12-04
  • 执行用时:92ms
  • 内存消耗:41MB
  • 编程语言:typescript
  • 解法介绍:遍历。
function canConstruct(ransomNote: string, magazine: string): boolean {
const map: Record<string, number> = {};
for (const c of magazine) map[c] = (map[c] ?? 0) + 1;
for (const c of ransomNote) {
if (!map[c]) return false;
map[c]--;
}
return true;
}

题解 2 - c

  • 编辑时间:2021-12-04
  • 执行用时:156ms
  • 内存消耗:6.4MB
  • 编程语言:c
  • 解法介绍:遍历。
bool canConstruct(char * ransomNote, char * magazine){
int ans[26] = {0};
for (int i = 0; i < strlen(magazine); i++) ans[magazine[i] - 'a']++;
for (int i = 0; i < strlen(ransomNote); i++) {
if (!ans[ransomNote[i] - 'a']) return 0;
ans[ransomNote[i] - 'a']--;
}
return 1;
}

题解 3 - python

  • 编辑时间:2024-01-07
  • 执行用时:48ms
  • 内存消耗:17.06MB
  • 编程语言:python
  • 解法介绍:遍历。
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
map = Counter(magazine)
for c in ransomNote:
map[c] -= 1
if map[c] < 0: return False
return True