Swift solution beating 100%


  • 0
    S
    class Solution {
        func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool {
            let rc = Array(ransomNote.unicodeScalars)
            let mc = Array(magazine.unicodeScalars)
            if rc.count > mc.count { return false }
            
            var counts = [Int](repeating: 0, count: 256)
            
            for i in 0..<mc.count {
                if i < rc.count { counts[Int(rc[i].value)] += 1 }
                counts[Int(mc[i].value)] -= 1
            }
            
            for val in counts {
                if val > 0 { return false }
            }
            
            return true
            
        }
    }
    

Log in to reply
 

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