Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

javascript anagram

const s = "anagram"
const t = "nagaram"

const isAnagram = function(s, t) {
    if (s.length !== t.length) {
        return false
    }

    const map_s = new Map()
    const map_t = new Map()

    for (let i = 0; i < s.length; i++) {
        if (map_s.has(s[i])) {
            map_s.set(s[i], map_s.get(s[i]) + 1)
        } else {
            map_s.set(s[i], 1)
        }

        if (map_t.has(t[i])) {
            map_t.set(t[i], map_t.get(t[i]) + 1)
        } else {
            map_t.set(t[i], 1)
        }
    }

    for (const s of map_s) {
        if (map_t.get(s[0]) !== s[1]) {
            return false
        }
    }

    console.log(map_s)
    console.log(map_t)
  	// [Log]:
    // Map(5) { 'a' => 3, 'n' => 1, 'g' => 1, 'r' => 1, 'm' => 1 }
    // Map(5) { 'n' => 1, 'a' => 3, 'g' => 1, 'r' => 1, 'm' => 1 }

    return true
};

console.log('
', isAnagram(s, t)) 	  // [Log]: true
 
PREVIOUS NEXT
Tagged: #javascript #anagram
ADD COMMENT
Topic
Name
8+8 =