From 8f58ab445a4f7a50a0a9d3ab9c2041dba0c1f2d9 Mon Sep 17 00:00:00 2001 From: Erincrying <1016158928@qq.com> Date: Tue, 11 Apr 2023 20:20:33 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=9B=B4=E6=96=B0242.=E6=9C=89=E6=95=88?= =?UTF-8?q?=E7=9A=84=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D=E8=AF=8D=EF=BC=8C?= =?UTF-8?q?js=E6=96=B9=E6=B3=95=EF=BC=8C=E9=87=87=E7=94=A8map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0242.有效的字母异位词.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index 1006ea35..ba802bbd 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -205,6 +205,19 @@ var isAnagram = function(s, t) { } return true; }; + +var isAnagram = function(s, t) { + if(s.length !== t.length) return false; + let char_count = new Map(); + for(let item of s) { + char_count.set(item, (char_count.get(item) || 0) + 1) ; + } + for(let item of t) { + if(!char_count.get(item)) return false; + char_count.set(item, char_count.get(item)-1); + } + return true; +}; ``` TypeScript: From eef44eb9e82c6f8c605e4e2575a3200dafe0014d Mon Sep 17 00:00:00 2001 From: Erincrying <1016158928@qq.com> Date: Tue, 11 Apr 2023 21:26:44 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E6=9B=B4=E6=96=B01002.=20=E6=9F=A5?= =?UTF-8?q?=E6=89=BE=E5=B8=B8=E7=94=A8=E5=AD=97=E7=AC=A6=EF=BC=8Cjs?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E9=87=87=E7=94=A8map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1002.查找常用字符.md | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index fd188660..9ec3c6c4 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -252,6 +252,36 @@ var commonChars = function (words) { } return res }; + +// 方法二:map() +var commonChars = function(words) { + let min_count = new Map() + // 统计字符串中字符出现的最小频率,以第一个字符串初始化 + for(let str of words[0]) { + min_count.set(str, ((min_count.get(str) || 0) + 1)) + } + // 从第二个单词开始统计字符出现次数 + for(let i = 1; i < words.length; i++) { + let char_count = new Map() + for(let str of words[i]) { // 遍历字母 + char_count.set(str, (char_count.get(str) || 0) + 1) + } + // 比较出最小的字符次数 + for(let value of min_count) { // 注意这里遍历min_count!而不是单词 + min_count.set(value[0], Math.min((min_count.get(value[0]) || 0), (char_count.get(value[0]) || 0))) + } + } + // 遍历map + let res = [] + min_count.forEach((value, key) => { + if(value) { + for(let i=0; i