<span style="font-family: Arial, Helvetica, sans-serif;">public:</span>
bool canConstruct(string ransomNote, string magazine) {
map<char,int> m;
int len1=ransomNote.size();
int len2=magazine.size();
int icount=0;
int fd=0;
if(len1>len2){return false;}
else
{
for (int i=0;i<len2;i++){
m[magazine[i]]++;
}
for (int j=0;j<len1;j++){
icount=m[ransomNote[j]];
if(icount!=0){
icount--;
m[ransomNote[j]]=icount;
fd++;
}
else
{ return false;}
}
if(fd==len1)
{return true;}
else return 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.
canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true