• + 0 comments

    My answer with Typescrip

    function anagram(s: string): number {
        // 0. check s length is odd, so it cann't be split, return -1
        if (s.length % 2 != 0) return -1
    
        // 1. split [s] into left part [l] and right part [r], define [m]&[o] to count
        let l = s.substring(0, s.length / 2)
        let r = s.substring(s.length / 2)
        let m = new Map<string, number>()
        let o = 0
    
        // 2. count [l] into [m], check [r], count++
        for (let c of l) m.set(c, (m.get(c) || 0) + 1)
        for (let c of r) {
            if (m.has(c) && m.get(c) > 0) m.set(c, m.get(c) - 1)
            else o++
        }
    
        // 3. return [o]
        return o
    }