mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #2027 from Erincrying/master
更新242.有效的字母异位词,js方法,采用map
This commit is contained in:
@ -205,6 +205,19 @@ var isAnagram = function(s, t) {
|
|||||||
}
|
}
|
||||||
return true;
|
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:
|
TypeScript:
|
||||||
|
@ -252,6 +252,36 @@ var commonChars = function (words) {
|
|||||||
}
|
}
|
||||||
return res
|
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<value; i++) {
|
||||||
|
res.push(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return res
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
TypeScript
|
TypeScript
|
||||||
|
Reference in New Issue
Block a user