Leetcode 383 ransom note #
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
Answer:
I have learnt that we can early return false if letterCount[char-'a'] < 0
func canConstruct(ransomNote string, magazine string) bool {
// Create an array to count the occurrences of each letter in the magazine
letterCount := [26]int{}
for _, char := range magazine {
letterCount[char-'a']++
}
// Check if the ransom note can be constructed from the magazine
for _, char := range ransomNote {
letterCount[char-'a']--
if letterCount[char-'a'] < 0 {
return false
}
}
return true
}