leetcode 383. Ransom Note HashMap查询加速
来源:互联网 发布:李强强 php 编辑:程序博客网 时间:2024/06/06 21:01
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 be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true
直接使用HashMap遍历即可。
代码如下:
import java.util.HashMap;import java.util.Map;class Solution { public boolean canConstruct(String ransomNote, String magazine) { if(ransomNote==null || magazine==null || ransomNote.length()>magazine.length()) return false; Map<Character, Integer> map=new HashMap<>(); for(int i=0;i<magazine.length();i++) map.put(magazine.charAt(i), map.getOrDefault(magazine.charAt(i), 0)+1); for(int i=0;i<ransomNote.length();i++) { if(map.containsKey(ransomNote.charAt(i))==false) return false; else { int size=map.get(ransomNote.charAt(i)); if(size==1) map.remove(ransomNote.charAt(i)); else map.put(ransomNote.charAt(i), size-1); } } return true; }}
阅读全文
0 0
- leetcode 383. Ransom Note HashMap查询加速
- leetcode-383. Ransom Note
- [leetcode] 383. Ransom Note
- LeetCode 383. Ransom Note
- leetcode 383. Ransom Note
- leetcode 383. Ransom Note
- 383.[LeetCode]Ransom Note
- leetcode 383. Ransom Note
- leetcode 383. Ransom Note
- Leetcode 383. Ransom Note
- 【leetcode】383. Ransom Note
- Leetcode 383. Ransom Note
- LeetCode 383. Ransom Note
- [LeetCode]383. Ransom Note
- LeetCode 383. Ransom Note
- [LeetCode]--383. Ransom Note
- LeetCode 383. Ransom Note
- leetcode 383. Ransom Note
- JS表单验证
- PageHelper分页插件源码及原理剖析
- Handler 使用方法详解
- request和response
- 第五周项目三
- leetcode 383. Ransom Note HashMap查询加速
- <!-- 自动推送工具代码-->
- 实验二 线性表-顺序表(JavaScript实现)
- Modbus 通讯协议数据帧之间的时间停顿间隔 “3.5字符”定义
- Linux——用户
- 堆和栈的区别(转)
- 2.3 Spring4 快速入门-bean 的注入与初始化和销毁
- AsyncTask异步处理
- Spark的性能调优