LeetCode -- Ransom Note
来源:互联网 发布:ubuntu启动mysql服务 编辑:程序博客网 时间:2024/05/21 14:09
题目描述:
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
就是输入两个字符串,判断ransom是否为magazine的子集。
考查的是哈希表,hash[字符,出现次数]先遍历magazine递增次数,再遍历ransom递减次数,如果:
hash[ransomNote[i]]没有包含返回false;
hash[ransomNote[i]]为负数,返回false。
实现代码:
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
就是输入两个字符串,判断ransom是否为magazine的子集。
考查的是哈希表,hash[字符,出现次数]先遍历magazine递增次数,再遍历ransom递减次数,如果:
hash[ransomNote[i]]没有包含返回false;
hash[ransomNote[i]]为负数,返回false。
实现代码:
public class Solution { public bool CanConstruct(string ransomNote, string magazine) { var hash = new Dictionary<char,int>();for(var i = 0;i < magazine.Length; i++){ if(!hash.ContainsKey(magazine[i])){ hash.Add(magazine[i],1); } else{ hash[magazine[i]]++; } } for(var i = 0;i < ransomNote.Length; i++){ if(!hash.ContainsKey(ransomNote[i])){return false; } else{ hash[ransomNote[i]] --; } } foreach(var k in hash.Keys){ if(hash[k] < 0){ return false; } } return true; }}
1 0
- leetcode-383. Ransom Note
- [leetcode] 383. Ransom Note
- LeetCode:383 Ransom Note
- 【Leetcode】Ransom Note
- LeetCode 383. Ransom Note
- Leetcode Ransom Note
- LeetCode#383 Ransom Note
- leetcode 383. Ransom Note
- leetcode 383. Ransom Note
- LeetCode: Ransom Note
- LeetCode Ransom Note(字符串)
- 383.[LeetCode]Ransom Note
- leetcode 383. Ransom Note
- leetcode 383. Ransom Note
- Leetcode 383. Ransom Note
- [Leetcode]Ransom Note
- [LeetCode] Ransom Note (java)
- LeetCode 383 Ransom Note
- C/C++编程小练习 计算10亿之内的素数和(合数筛选算法实现)
- APACHE配置
- 测试小故事21:语言的力量
- Linux文件系统底层实现
- flume_kafka联合使用
- LeetCode -- Ransom Note
- Linux下的C语言编程——进程间通过signal函数通信简单操作
- java中类方法与对象方法区别
- Dynamic ODT
- 竖式问题--c
- LeetCode -- Divide Two Integers
- javaScript创建对象
- matlab PCA-SVD简单地实现特征脸方法(Eigenface)
- java.lang.UnsupportedClassVersionError的产生原因和解决办法深度剖析