LeetCode 0383 Ransom Note【贖金信,哈希】

題目鏈接 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.

Example 1:

Input: ransomNote = "a", magazine = "b"
Output: false

Example 2:

Input: ransomNote = "aa", magazine = "ab"
Output: false

Example 3:

Input: ransomNote = "aa", magazine = "aab"
Output: true

Constraints:

  • You may assume that both strings contain only lowercase letters.

題意

  • 看字符串ransomNote能否被字符串 magazine 構造出來,magazine中的每個字符只允許被使用一次

  • 字符串中僅包含小寫字母

思路1

  • 使用一個哈希表記錄下 magazine 中每個字符出現次數
  • 遍歷 ransomNote 中每個字符,每次將哈希表中的次數減1,若出現減完之後的結果小於0,則顯然不符,否則可以。

代碼1

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int cnt[26] = {0};
        for(const auto &it : magazine)
            cnt[it - 'a']++;
        bool ans = true;
        for(const auto &it : ransomNote)
        {
            if(cnt[it - 'a'])
                cnt[it - 'a']--;
            else
            {
                ans = false;
                break;
            }
        }
        return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章