首页 > 其他分享 >哈希表 - 赎金信

哈希表 - 赎金信

时间:2024-08-13 14:28:00浏览次数:12  
标签:ransomNote return 哈希 param magazine charCodeAt 赎金 const

383. 赎金信

在这里插入图片描述

方法一:哈希表

/**
 * @param {string} ransomNote
 * @param {string} magazine
 * @return {boolean}
 */
var canConstruct = function(ransomNote, magazine) {
    const strArr = new Array(26).fill(0), base = "a".charCodeAt();
    for (const s of magazine) {  // 记录magazine里各个字符出现次数
        strArr[s.charCodeAt() - base]++;
    }
    for (const s of ransomNote) {  // 对应的字符个数做--操作
        const index = s.charCodeAt() - base;
        if (!strArr[index]) return false;  // 如果没记录过直接返回false
        strArr[index]--;
    }
    return true;
};

方法二:字符统计

/**
 * @param {string} ransomNote
 * @param {string} magazine
 * @return {boolean}
 */
var canConstruct = function(ransomNote, magazine) {
    if (ransomNote.length > magazine.length) {
        return false;
    }
    const cnt = new Array(26).fill(0);
    for (const c of magazine) {
        cnt[c.charCodeAt() - 'a'.charCodeAt()]++;
    }
    for (const c of ransomNote) {
        cnt[c.charCodeAt() - 'a'.charCodeAt()]--;
        if(cnt[c.charCodeAt() - 'a'.charCodeAt()] < 0) {
            return false;
        }
    }
    return true;
};

方法三:暴力解法

/**
 * @param {string} ransomNote
 * @param {string} magazine
 * @return {boolean}
 */

var canConstruct = function(ransomNote, magazine) {
    for (let i = 0; i < magazine.length; i++) {
        for (let j = 0; j < ransomNote.length; j++) {
            // 在ransomNote中找到和magazine相同的字符
            if (magazine[i] === ransomNote[j]) {
                ransomNote.splice(ransomNote[j], 1); // ransomNote删除这个字符串
            }
        }
    }
    // 如果ransomNote为空,则说明magazine的字符可以组成ransomNote
    if (ransomNote.length === 0) {
        return true;
        console.log("magazine的字符可以组成ransomNote");
    }
    return false;
    console.log("magazine的字符不可以组成ransomNote");
};

let a = canConstruct(["a", "a", "c"], ["a", "a", "b", "c"]);
console.log(a);

标签:ransomNote,return,哈希,param,magazine,charCodeAt,赎金,const
From: https://blog.csdn.net/2203_75300307/article/details/141158045

相关文章