[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其他代码也是这个思路,略

posted @ 2018-08-14 11:20  arcsinW  阅读(103)  评论(0编辑  收藏  举报