Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript anagram two strings

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
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript function to open file browser 
Javascript :: how would you check if a number is an integer in javascript 
Javascript :: node main 
Javascript :: set cookie in reactjs 
Javascript :: python pretty print json command line 
Javascript :: Uncaught TypeError: .replace is not a function 
Javascript :: Round to at most 2 decimal places 
Javascript :: javascript text replace 
Javascript :: npm fund error 
Javascript :: js scroll to id on body 
Javascript :: js notifications 
Javascript :: javascript splice without changing array 
Javascript :: js tolowercase 
Javascript :: .filter js 
Javascript :: password confirmation using Joi 
Javascript :: byte to mb js 
Javascript :: js get class property 
Javascript :: avascript regex email 
Javascript :: mssql node js documentation 
Javascript :: jest to include text 
Javascript :: define an unsigned int js 
Javascript :: how to make a div appear when clicked on in javascript 
Javascript :: javascript change color every second 
Javascript :: get the text of a tag 
Javascript :: Passing components as children in react 
Javascript :: mongoose multiple populate 
Javascript :: how to get the size of the window in javascript 
Javascript :: select elements of an array starting by a certain letter javascript 
Javascript :: typescript express next middleware type 
Javascript :: numbered occurences in regex 
ADD CONTENT
Topic
Content
Source link
Name
6+2 =