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