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