383. Ransom Note--哈希的方法
2017-02-28 20:45
204 查看
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
方法一、采用c++的map来实现,代码:
方法二、采用数组来实现,代码:
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
方法一、采用c++的map来实现,代码:
bool canConstruct(string ransomNote, string magazine) { //采用c++的map来实现 map<char,int> mapNum; for(int i = 0; i < magazine.length(); i++){ mapNum[magazine[i]]++; } for(int i = 0; i < ransomNote.length(); i++){ if(--mapNum[ransomNote[i]] < 0) return false; } return true; }
方法二、采用数组来实现,代码:
bool canConstruct(string ransomNote, string magazine) { vector<int> vec(26, 0); for (int i = 0; i < magazine.size(); ++i) ++vec[magazine[i] - 'a']; for (int j = 0; j < ransomNote.size(); ++j) if (--vec[ransomNote[j] - 'a'] < 0) return false; return true; }
相关文章推荐
- LeetCode oj 383. Ransom Note(哈希)
- php中session出现warning或note提示 解决方法
- outlook notepaper 中出现RUNTIME ERROR解决方法
- 转载和积累系列 - 解决哈希(HASH)冲突的主要方法
- POJ3432《Count Squares》方法:哈希
- 哈希查找方法经典题型
- 解决哈希(HASH)冲突的主要方法
- 【spring NOTE】调用实例工厂方法创建Bean
- POJ3274《Gold Balanced Lineup》方法:哈希
- POJ2002《Squares》方法:哈希
- 哈希崩溃及避免方法
- HashMap,哈希表,哈希方法
- 哈希方法
- error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 解决方法
- linux-programming-note-6(基本进程间通信方法)
- C# 中使用 MD5 算法计算 hash (哈希)值的四种方法
- C# 中使用 MD5 算法计算 hash (哈希)值的四种方法
- 软件工程:实践者的研究方法-note20101215
- 解决哈希(HASH)冲突的主要方法
- 使用 PHP 5.5 创建和验证哈希最简单的方法