【Question】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.

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.
Insert picture description here

answer

Insert picture description here
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;
}

Guess you like

Origin blog.csdn.net/m0_46613023/article/details/113864208