1. 程式人生 > >[LeetCode] 383. Ransom Note

[LeetCode] 383. Ransom Note

cti letters note not ngs result 多個 etc ons

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