【刷题】383. 赎金信——给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。

题目:383. 赎金信

给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。
在这里插入图片描述

解答

在这里插入图片描述
思路:绝对位置

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;
}

思路:相对位置

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;
}

猜你喜欢

转载自blog.csdn.net/m0_46613023/article/details/113864208
今日推荐