Subject: 383. Ransom Letter
Given a ransom letter (ransom) string and a magazine (magazine) string, determine whether the first string ransom can be composed of the characters in the second string magazines. If it can be formed, return true; otherwise, return false.
answer
Idea: Absolute position
bool canConstruct(char* ransomNote, char* magazine)
{
int ASCLL[130] = {
0};
while(*magazine != '\0')
{
ASCLL[*magazine]++;
magazine++;
}
while(*ransomNote != '\0')
{
ASCLL[*ransomNote]--;
ransomNote++;
}
for(int i = 0;i < 130;i++)
{
if(ASCLL[i] < 0)
return false;
}
return true;
}
Idea: Relative position
bool canConstruct(char * ransomNote, char * magazine){
int ASCLL[26]={
0};
while (*magazine != '\0')
{
ASCLL[*magazine -'a']++;
magazine++;
}
while (*ransomNote != '\0')
{
ASCLL[*ransomNote-'a']--;
if (ASCLL[*ransomNote-'a']<0)
{
return false;
}
ransomNote++;
}
return true;
}