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") -> truesolution with C
思路:因为题目中的字符串全是小写,可以设置一个26个元素的数组int map[26]用来保存对应字母在magazine字串中出现的次数,map[0]代表‘a'在magazine中出现的次数.....map[25]代表'z'在magazine中出现的次数,这些可以在遍历magazine的时候实现,ok,在对ransomNote进行遍历,此时对每个在ransomNote中的字符对应的map的位置进行-1操作,最后判断map里面是否有<0的数字,即可返回true or false
bool canConstruct(char* ransomNote, char* magazine) {
if (strlen(ransomNote)>strlen(magazine))
return false;
int map[26] = { 0 };
char* p = magazine;
for (int i = 0; i != strlen(magazine); ++i)
{
map[*p - 'a'] += 1;
++p;
}
p = ransomNote;
for (int i = 0; i != strlen(ransomNote); ++i)
{
map[*p - 'a'] -= 1;
if (map[*p - 'a']<0)
return false;
++p;
}
return true;
}