Created
July 16, 2020 15:22
-
-
Save wangcaipang/771dadb84b4336d10c3c58f754b75b5c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} s | |
* @param {string} p | |
* @return {number[]} | |
*/ | |
var findAnagrams = function(s, p) { | |
const target = p.split("").reduce((res, c) => { | |
res[c] = (res[c] || 0) + 1; | |
return res; | |
}, {}); | |
var cacheMap = {}; | |
var indexMap = p.split("").reduce((res, c) => { | |
res[c] = []; | |
return res; | |
}, {}); | |
const res = []; | |
let j = 0; | |
while(j < s.length) { | |
const curCh = s[j]; | |
if(target[curCh] === undefined) { | |
Object.keys(indexMap).forEach(ch => { | |
indexMap[ch] = []; | |
}); | |
} else{ | |
indexMap[curCh].push(j); | |
if(indexMap[curCh].length > target[curCh]) { | |
const firstInx = indexMap[curCh][0]; | |
Object.keys(indexMap).forEach(ch => { | |
console.log(curCh, firstInx); | |
indexMap[ch] = indexMap[ch].filter(i => i > firstInx); | |
}); | |
} | |
const isRight = !Object.keys(indexMap).find(ch => indexMap[ch].length !== target[ch]); | |
if(isRight) { | |
const startIdx = Math.min(...Object.keys(indexMap).map(ch => indexMap[ch][0])); | |
res.push(startIdx); | |
} | |
} | |
j = j + 1; | |
} | |
return res; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment