[LeetCode] 383. Ransom Note

Posted arcsinw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 383. Ransom Note相关的知识,希望对你有一定的参考价值。

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

Note:

You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

两个字符串输入参数,判断第二个string是否能拼出第一个字符串
第二个字符串象是一本杂志,从杂志里剪出很多个字符拼成第一个字符串,所以要有对应的字符而且数量要足够

能很简单地写出一个非最优解版本

bool canConstruct(string ransomNote, string magazine)
{
    int dic1[26] = {0};
    int dic2[26] = {0};
    for(char c : ransomNote)
    {
        dic1[c-‘a‘]++;
    }

    for(char c : magazine)
    {
        dic2[c-‘a‘]++;
    }

    bool result = true;
    for(int i = 0; i < 26, dic1[i] !=0; i++)
    {
        if (dic1[i] > dic2[i])
        {
            result = false;
        }
    }

    return result;
}

再把一些步骤合并起来,可以只统计magazine的字符数量,直接在ransomNote的循环中判断字符数量是否足够

bool canConstruct(string ransomNote, string magazine) 
{
    int dic1[26] = {0};

    for (char c : magazine)
    {
        dic1[c - ‘a‘]++;
    }

    for(char c : ransomNote)
    {
        if (dic1[c - ‘a‘] == 0)
        {
            return false;
        }

        dic1[c - ‘a‘]--;
    }

    return true;
}

LeetCode其他代码也是这个思路,略


以上是关于[LeetCode] 383. Ransom Note的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 383. Ransom Note

LeetCode(383)Ransom Note

LeetCode 383 Ransom Note

LeetCode 383 Ransom Note

Leetcode 383 Ransom Note

[leetcode-383-Ransom Note]