[Algorithm] Determine if two strings are an anagram

本文介绍了一种使用Map数据结构来高效判断两个字符串是否为anagram的方法,并通过具体示例展示了其实现过程。

The anagram test is commonly used to demonstrate how an naive implementation can perform significant order of magnitudes slower than an efficient one. We’ll also briefly go over why each implementation is not as efficient as you could make it.

A word is an anagram of another if you can rearrange its characters to produce the second word. Here we’ll write multiple increasingly more efficient functions that given two strings determines if they are anagrams of each other.

 

const str1 = "earth";
const str2 = "heart";

/**
 *  Map {
 *     e: 0,
 *     a: 0,
 *     r: 0,
 *     t: 0,
 *     h: 0
 *  }
 *
 */

// Using Map is much easier to set, get, check (has) value
function areAnagrams(str1, str2) {
  const mapping = new Map();
  for (let char of str1.split("")) {
    mapping.set(char, (mapping.get(char) || 0) + 1);
  }

  for (let char of str2.split("")) {
    if (mapping.has(char)) {
      mapping.set(char, mapping.get(char) - 1);
    }
  }

  // Conver Map values to Array
  return Array.from(mapping.values()).every(v => v === 0);
}

const res = areAnagrams(str1, str2);

console.log(res); // true

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值