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
这道题目不要误解了,不是子集的意思,实际上是后者的元素够不够组成前面的字符串,比较简单的思想就是利用26字母进行计数
这里用的是unordermap(哈希表), 也可以用数组,下标用‘magzine[i]’-'a'来表示
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
bool canConstruct(string ransomNote, string magazine) {
int ran_num = ransomNote.length();
int mag_num = magazine.length();
unordered_map <char,int> map(26);
for (int i = 0; i < mag_num; ++i) {
++map[magazine[i]];
}
for (int j = 0; j < ran_num; ++j) {
if(--map[magazine[j]]<0)
return false;
}
return true;
}
int main() {
std::string a = "aa";
std::string b = "aab";
unordered_map<char ,int > test(10);
std::cout<<test['a']<<endl;
std::cout << canConstruct(a,b) << std::endl;
return 0;
}
这里要注意的是,当申明unordered_map <char,int> map(26);
当我们直接出一个char的时候,int默认为0.
注意哈希表和map的区别,map可不能这么用