博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Ransom Note
阅读量:7289 次
发布时间:2019-06-30

本文共 1308 字,大约阅读时间需要 4 分钟。

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 .

public class Solution {    public boolean canConstruct(String ransomNote, String magazine) {        HashMap
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 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.

转载于:https://www.cnblogs.com/jcliBlogger/p/5771151.html

你可能感兴趣的文章
[转]Web Service与WCF区别
查看>>
vs2010 .net4.0 错误 事件的显式接口实现必须使用事件访问器语法
查看>>
BZOJ1090:[SCOI2003]字符串折叠——题解
查看>>
Python网络爬虫-爬取微博热搜
查看>>
js 与或运算符 || && 妙用
查看>>
react-conponent-secondesElapsed
查看>>
DFS 10.1.5.253 1501
查看>>
vue 项目分享
查看>>
smb
查看>>
3.算法-二叉树遍历
查看>>
File类
查看>>
基于层次关联的鲁棒多目标跟踪
查看>>
Python基础---异常
查看>>
动态调用WebService 通用方法Moss 中 传统开发中都可用。
查看>>
【cocos2d-x 024】 LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
查看>>
概述C# Cast()
查看>>
LeetCode - 9. Palindrome Number
查看>>
IOS的 new Date()格式化问题
查看>>
sharepoint webpart 获取文档库下的所有文件夹名
查看>>
java数据结构和算法--------第六章
查看>>