Skip to content

Instantly share code, notes, and snippets.

@ufo22940268
Created April 26, 2021 05:50
Show Gist options
  • Save ufo22940268/1f0489b55c390bf1b98000428859cbf0 to your computer and use it in GitHub Desktop.
Save ufo22940268/1f0489b55c390bf1b98000428859cbf0 to your computer and use it in GitHub Desktop.
//Given two strings s and p, return an array of all the start indices of p's ana
//grams in s. You may return the answer in any order.
//
//
// Example 1:
//
//
//Input: s = "cbaebabacd", p = "abc"
//Output: [0,6]
//Explanation:
//The substring with start index = 0 is "cba", which is an anagram of "abc".
//The substring with start index = 6 is "bac", which is an anagram of "abc".
//
//
// Example 2:
//
//
//Input: s = "abab", p = "ab"
//Output: [0,1,2]
//Explanation:
//The substring with start index = 0 is "ab", which is an anagram of "ab".
//The substring with start index = 1 is "ba", which is an anagram of "ab".
//The substring with start index = 2 is "ab", which is an anagram of "ab".
//
//
//
// Constraints:
//
//
// 1 <= s.length, p.length <= 3 * 104
// s and p consist of lowercase English letters.
//
// Related Topics 哈希表
// 👍 514 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
/**
* @param {string} s
* @param {string} p
* @return {number[]}
*/
var findAnagrams = function (s, p) {
const ret = [];
const pc = Array.from(p).reduce((ar, c) => {
ar[c.charCodeAt(0)] += 1;
return ar;
}, new Array(400).fill(0))
let cur = pc.slice();
let winFrom = 0;
let winTo = 0;
let count = p.length;
while (true) {
if (winTo == s.length) break;
if (cur[s[winTo].charCodeAt(0)] > 0) {
cur[s[winTo].charCodeAt(0)] -= 1;
count -= 1;
if (count == 0) {
ret.push(winFrom);
winFrom = winFrom + 1
winTo = winFrom;
cur = pc.slice();
count = p.length;
} else {
winTo = winTo + 1;
}
} else {
winFrom = winFrom + 1
winTo = winFrom
cur = pc.slice();
count = p.length;
}
}
return ret;
};
//leetcode submit region end(Prohibit modification and deletion)
const r = findAnagrams("cbaebabacd", "abc")
// const r = findAnagrams("abab", "ab")
console.log(`r: ` + JSON.stringify(r, null, 4) + '\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment