Algorithms first
赎金信 · 交互式算法学习
判断杂志字符能否拼出赎金信,每个字符只能使用一次。
#383 · 哈希表
赎金信
Ransom Note
ransomNote = "aa", magazine = "aab"线性序列3 个关键状态
步骤 1统计 magazine。
{a:2,b:1}a
0a
1b
2推荐
字符频次表
时间
O(n+m)空间 O(字符集)先统计杂志字符,消耗时若计数为零则失败。
1function canConstruct(note, mag) {2 const count = {};3 for (const c of mag) count[c] = (count[c] || 0) + 1;4 for (const c of note)5 if (!count[c]--) return false;6 return true;7}多语言参考
来源 · CC BY-SA 4.0 ↗Java · C++ · Go
这是一组同题正确实现,独立于上方当前动画方法;不同语言可能采用另一种正确策略。
1class Solution {2 public boolean canConstruct(String ransomNote, String magazine) {3 int[] cnt = new int[26];4 for (int i = 0; i < magazine.length(); ++i) {5 ++cnt[magazine.charAt(i) - 'a'];6 }7 for (int i = 0; i < ransomNote.length(); ++i) {8 if (--cnt[ransomNote.charAt(i) - 'a'] < 0) {9 return false;10 }11 }12 return true;13 }14}交互式算法学习
从执行步骤真正理解 LeetCode 经典 150
本站整理 150 道高频算法面试题和 302 种解法。动画方法同步展示 JavaScript 与 Python;每题另提供 Java、C++ 与 Go 同题参考实现。
AlgoViz Lab
赎金信 · 解法对比
判断杂志字符能否拼出赎金信,每个字符只能使用一次。
- 测试用例
ransomNote = "aa", magazine = "aab"- 题目分类
- 哈希表
- 解法对比
- 2
逐字符删除
每需要一个字符,就在可用字符数组中查找并删除。
- 时间
O(n²)- 空间
O(n)
字符频次表
先统计杂志字符,消耗时若计数为零则失败。
- 时间
O(n+m)- 空间
O(字符集)