Skip to content

Instantly share code, notes, and snippets.

@wangcaipang
Created July 16, 2020 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wangcaipang/771dadb84b4336d10c3c58f754b75b5c to your computer and use it in GitHub Desktop.
Save wangcaipang/771dadb84b4336d10c3c58f754b75b5c to your computer and use it in GitHub Desktop.
/**
* @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