Swift, use dictionary to record frequency of letters in magazine, O(n) space


  • 0
    X
    class Solution {
        func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool {
            
            // A : use dict to record each letter and thier freq, then subtrack ransomNote letters
            var dict = [String:Int]()
            for char in magazine.characters {
                if let freq = dict[String(char)] {
                    dict[String(char)]! += 1
                }else{
                    dict[String(char)] = 1
                }
            }
            for char in ransomNote.characters {
                if let freq = dict[String(char)] {
                    if freq == 0 { return false }
                    dict[String(char)]! = freq - 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.