forked from sl1673495/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path找到字符串中所有字母异位词-438.js
59 lines (53 loc) · 1.11 KB
/
找到字符串中所有字母异位词-438.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* @param {string} s
* @param {string} p
* @return {number[]}
*/
let findAnagrams = function (s, p) {
let targetMap = makeCountMap(p)
let sl = s.length
let pl = p.length
// [left,...right] 滑动窗口
let left = 0
let right = pl - 1
let windowMap = makeCountMap(s.substring(left, right + 1))
let res = []
while (left <= sl - pl && right < sl) {
if (isAnagrams(windowMap, targetMap)) {
res.push(left)
}
windowMap[s[left]]--
right++
left++
addCountToMap(windowMap, s[right])
}
return res
}
let isAnagrams = function (windowMap, targetMap) {
let targetKeys = Object.keys(targetMap)
for (let targetKey of targetKeys) {
if (
!windowMap[targetKey] ||
windowMap[targetKey] !== targetMap[targetKey]
) {
return false
}
}
return true
}
function addCountToMap(map, str) {
if (!map[str]) {
map[str] = 1
} else {
map[str]++
}
}
function makeCountMap(strs) {
let map = {}
for (let i = 0; i < strs.length; i++) {
let letter = strs[i]
addCountToMap(map, letter)
}
return map
}
console.log(findAnagrams("abab", "ab"))