Game of Thrones - I

  • + 0 comments

    My answer with Typescript, noted

    function gameOfThrones(key: string): string {
        // 0. define a map, couting [char] in [key]
        let hash = new Map<string, number>()
        for (let c of key) hash.set(c, (hash.get(c) || 0) + 1)
        
        // 1. define some variable
        let key_is_odd: boolean = key.length % 2 != 0
        let flag: boolean = true
    
        // 2. loop hash and check [char_count] of each [char]...
        for (const char_count of hash.values()) {
            const char_count_is_odd = char_count % 2 != 0
            
            // 2.1 [char_count] that divided by 2, mean it can be split 2 side
            //  -> skip check
            // 2.2 [char_count] that not divided by 2, but [key] is 
            //  -> there is at least one extra char, return NO
            // 2.3 [char_count] and [key] is both odd, it can be have only 1 extra char
            //  -> if have more than 1, return NO
            //  -> set flag = false to know that already have 1
            if (!char_count_is_odd) continue
            if (!key_is_odd) return 'NO'
            if (!flag) return 'NO'
    
            flag = false
        }
    
        return 'YES'
    }