Home LeetCode - 383. Ransom Note
Post
Cancel

LeetCode - 383. Ransom Note

383. Ransom Note - easy

문제

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.

제한사항

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

입출력 예

1
2
3
4
5
Example 1:

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

풀이

  • Hash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func canConstruct(ransomNote string, magazine string) bool {
    m := make(map[rune]int)
    
    for _,v := range(magazine) {
        m[v]++    
    }
    
    for _,v := range(ransomNote) {
        i, exist := m[v]
        
        if(!exist || i == 0) {
            return false;
        } else {
            m[v]--
        }
    }
    
    return true;
}
This post is licensed under CC BY 4.0 by the author.