0383. Ransom Note

# 383. Ransom Note#

## 题目 #

Given two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

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:

• 1 <= ransomNote.length, magazine.length <= 100000
• ransomNote and magazine consist of lowercase English letters.

## 题目大意 #

magazine 中的每个字符只能在 ransomNote 中使用一次。

## 解题思路 #

• ransomNote 和 magazine 都是由小写字母组成，所以用数组进行简单的字符统计

## 代码 #

``````package leetcode

func canConstruct(ransomNote string, magazine string) bool {
if len(ransomNote) > len(magazine) {
return false
}
var cnt [26]int
for _, v := range magazine {
cnt[v-'a']++
}
for _, v := range ransomNote {
cnt[v-'a']--
if cnt[v-'a'] < 0 {
return false
}
}
return true
}
``````

Apr 8, 2023