2021-12-4(LeetCode每日一题)

133 阅读1分钟

赎金信

image.png

代码

var canConstruct = function(ransomNote, magazine) {
    const { length: m } = ransomNote;
    const { length: n } = magazine;

    if (n < m) return false;

    const cnt = new Array(26).fill(0);
    const start = 'a'.charCodeAt();
    for (let i = 0; i < n; ++i) {
        ++cnt[magazine[i].charCodeAt() - start];
    }

    for (let i = 0; i < m; ++i) {
        const index = ransomNote[i].charCodeAt() - start;
        if (!cnt[index]) {
            return false;
        }
        --cnt[index];
    }

    return true;
};

题解

  • 根据题意我们采用计数模拟方法进行解答。由于ransomNote和magazine仅由小写英文字母组成,所以我们使用长度为26的数组记录magazine中每个字母出现的次数,然后遍历ransomNote对数组进行抵消操作,如果数组中的值小于0,表示ransomNote不能由magazine构成。

注意事项

  • 如果magazine的长度小于ransomNote的长度,直接返回false,没必要进行后续模拟。