[LeetCode] Ransom Note

简介: A very typical application of hash maps. Since I am now learning Java, I code in Java. The following code uses toCharArray() and getOrDefault(), which are learnt from this post.

A very typical application of hash maps. Since I am now learning Java, I code in Java. The following code uses toCharArray() and getOrDefault(), which are learnt from this post.

public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        HashMap<Character, Integer> map = new HashMap<>();
        for (Character k : magazine.toCharArray()) {
            int v = map.getOrDefault(k, 0) + 1;
            map.put(k, v);
        }
        for (Character k : ransomNote.toCharArray()) {
            int v = map.getOrDefault(k, 0) - 1;
            if (v < 0) return false;
            map.put(k, v);
        }
        return true;
    }
}

This code takes about 60ms.

In fact, arrays can be used to replace hash maps since the test cases of this problem only contan the 26 English letters. A array-version solution can be found here and is rewritten below.

public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] map = new int[26];
        for (char k : magazine.toCharArray())
            map[k - 'a']++;
        for (char k : ransomNote.toCharArray()) {
            int v = --map[k - 'a'];
            if (v < 0) return false;
        }
        return true;
    }
}

This version is much faster, about 13ms.

目录
相关文章
LeetCode 383. Ransom Note
给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false。
68 0
LeetCode 383. Ransom Note
LeetCode之Ransom Note
LeetCode之Ransom Note
114 0
[LeetCode]--383. Ransom Note

Given
 an 
arbitrary
 ransom
 note
 string 
and 
another 
string 
containing 
letters from
 all 
the 
magazines,
 write 
a 
function 
that 
will 
return 
true 
if 
the 
ransom 
 note 
can
1332 0
|
28天前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
2月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
50 6
|
2月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
99 2
|
28天前
|
数据采集 负载均衡 安全
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口
本文提供了多个多线程编程问题的解决方案,包括设计有限阻塞队列、多线程网页爬虫、红绿灯路口等,每个问题都给出了至少一种实现方法,涵盖了互斥锁、条件变量、信号量等线程同步机制的使用。
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口