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.

The best we can do is O(n).

The way is using hashed map, in Javascript or TypeScirpt, we can use Map.

Just simply loop over stirng1 array and set counter for each char. Everytime +1.

Then second loop over string2 array set decrease the counter, if there is a char which is not in the hashed map then two strings are not anagram.

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

最新文章

  1. Linux图形&命令行界面切换
  2. 【原创】Kakfa message包源代码分析
  3. 解决PHP生成UTF-8编码的CSV文件用Excel打开乱码的问题
  4. 化简复杂逻辑,编写紧凑的if条件语句
  5. IE6的bug
  6. 用了好多年的XP换成了Win7
  7. DB数据导出工具分享
  8. spring aop 基于schema的aop
  9. 使用Java理解逻辑程序
  10. 章节十、4-CSS Classes---用多个CSS Classes定位元素
  11. mysql MHA高可用测试
  12. C++ 实验2
  13. python四
  14. Class 泛型
  15. PAT甲级题解-1066. Root of AVL Tree (25)-AVL树模板题
  16. 7.4 C++标准模板库(STL)的概念
  17. Lambda架构
  18. signal函数的原型声明void (*signal(int signo, void (*fun(int))))(int)分析
  19. sql ltrim/rtrim 字段中为中文时出现?的问题
  20. 41-mysql作业

热门文章

  1. JavaScript设计模式 (1) 原型模式
  2. Concurrent control in SQLite
  3. 防止按钮button重复提交,点击后失效,10秒后恢复
  4. 字符编码方式ASCII、Unicode、UTF-8
  5. docloud后台管理项目(开篇)
  6. HDU_1114_piggy-bank
  7. RabbitMQ系列(七)--批量消息和延时消息
  8. vue基础---条件渲染
  9. 05Servlet example
  10. UVA - 1608 Non-boring sequences(分治法)