Javascript 为什么不是';这个解决方案行不通吗?使用两个映射查找常用字符
这是leetcode的一个问题。问题描述是 给定一个仅由小写字母组成的字符串数组,返回列表中所有字符串中显示的所有字符的列表(包括重复字符)。例如,如果一个字符在所有字符串中出现3次,但不是4次,则需要在最终答案中包含该字符3次 我尝试使用两个映射实现一个解决方案,但它不起作用。有人能告诉我原因吗?提前谢谢Javascript 为什么不是';这个解决方案行不通吗?使用两个映射查找常用字符,javascript,dictionary,Javascript,Dictionary,这是leetcode的一个问题。问题描述是 给定一个仅由小写字母组成的字符串数组,返回列表中所有字符串中显示的所有字符的列表(包括重复字符)。例如,如果一个字符在所有字符串中出现3次,但不是4次,则需要在最终答案中包含该字符3次 我尝试使用两个映射实现一个解决方案,但它不起作用。有人能告诉我原因吗?提前谢谢 var commonChars = function(A) { let resultMap = new Map(); let map = new Map(); let
var commonChars = function(A) {
let resultMap = new Map();
let map = new Map();
let result = [];
var fillmap = function(map, string){
for(let i=0; i<string.length; i++){
if(map.has(string[i])){
map.set(string[i], map.get(string[i])+1);
}else{
map.set(string[i], 1);
}
}
};
fillmap(resultMap, A[0]);
for(let j=1; j<A.length; j++){
fillmap(map, A[j]);
for(var key in resultMap){
if(!map.has(key)){
resultMap.delete(key);
}else if(map.get(key) < resultMap.get(key)){
resultMap.set(key, map.get(key));
}
}
map.clear();
}
for(var key in resultMap){
for(let k=0; k<resultMap.get(key); k++){
result.push(key);
}
}
return result;
};
var commonChars=函数(A){
让resultMap=newmap();
设map=newmap();
让结果=[];
var fillmap=函数(映射,字符串){
例如(设i=0;i贴图没有键(从某种意义上讲,它是一个对象,就像JS中的所有东西一样,作为一个对象,它没有键(它继承了.size
和其他)。要获取贴图的键,请使用.keys()
。因此(除其他外):
必须是:
for(let key of resultMap.keys())
我会这样做(是的,我无法抗拒挑战——如果你还没有自己解决它,就停止阅读!):
const commonChars=input=>input.reduce(
(重复,str)=>str.split(“”)过滤器(c=>dupes.includes(c)和&重复拼接(dupes.indexOf(c),1)),
输入[0]。拆分(“”)
);
for(let key of resultMap.keys())
const commonChars = input => input.reduce(
(dupes, str) => str.split("").filter(c => dupes.includes(c) && dupes.splice(dupes.indexOf(c), 1)),
input[0].split("")
);