Swift solution - Hash Table


  • 0
    class Solution {
        func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool {
            let ransomChars = Array(ransomNote.characters)
            let magazineChars = Array(magazine.characters)
            var dict = [Character: Int]()
            
            for char in magazineChars {
                if let value = dict[char] {
                    dict[char] = value + 1
                } else {
                    dict[char] = 1
                }
            }
            
            for char in ransomChars {
                if let value = dict[char] {
                    if value - 1 < 0 {
                        return false
                    }
                    dict[char] = value - 1
                } else {
                    return false
                }
            }
            
            return true
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.