|
| 1 | +/* |
| 2 | +Find All Anagrams in a String |
| 3 | +https://leetcode.com/problems/find-all-anagrams-in-a-string/ |
| 4 | +
|
| 5 | +Given two strings s and p, return an array of all the start indices of p's anagrams in s. |
| 6 | +You may return the answer in any order. |
| 7 | +
|
| 8 | +An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, |
| 9 | +ypically using all the original letters exactly once. |
| 10 | +
|
| 11 | +Example 1: |
| 12 | +
|
| 13 | +Input: s = "cbaebabacd", p = "abc" |
| 14 | +Output: [0,6] |
| 15 | +Explanation: |
| 16 | +The substring with start index = 0 is "cba", which is an anagram of "abc". |
| 17 | +The substring with start index = 6 is "bac", which is an anagram of "abc". |
| 18 | +Example 2: |
| 19 | +
|
| 20 | +Input: s = "abab", p = "ab" |
| 21 | +Output: [0,1,2] |
| 22 | +Explanation: |
| 23 | +The substring with start index = 0 is "ab", which is an anagram of "ab". |
| 24 | +The substring with start index = 1 is "ba", which is an anagram of "ab". |
| 25 | +The substring with start index = 2 is "ab", which is an anagram of "ab". |
| 26 | +*/ |
| 27 | + |
| 28 | +/** |
| 29 | + * @param {string} s |
| 30 | + * @param {string} p |
| 31 | + * @return {number[]} |
| 32 | + */ |
| 33 | + var findAnagrams = function(s, p) { |
| 34 | + if(s.length < p.length) { return [] } |
| 35 | + |
| 36 | + let start = 0; |
| 37 | + let end = p.length - 1; |
| 38 | + let hashBuild = {}; |
| 39 | + let countLeft = p.length; |
| 40 | + let anagrams = [] |
| 41 | + |
| 42 | + for(let e = 0; e < p.length; e++) { |
| 43 | + hashBuild[p[e]] = hashBuild[p[e]] !== undefined ? hashBuild[p[e]] + 1 : 1; |
| 44 | + } |
| 45 | + |
| 46 | + for(let i = start; i < end; i++) { |
| 47 | + if(hashBuild[s[i]] !== undefined) { |
| 48 | + hashBuild[s[i]] = hashBuild[s[i]] - 1; |
| 49 | + if(hashBuild[s[i]] >= 0) { |
| 50 | + countLeft--; |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + while(end < s.length) { |
| 56 | + // check left |
| 57 | + if(hashBuild[s[end]] !== undefined) { |
| 58 | + hashBuild[s[end]] = hashBuild[s[end]] - 1; |
| 59 | + if(hashBuild[s[end]] >= 0) { |
| 60 | + countLeft--; |
| 61 | + } |
| 62 | + if(countLeft == 0) { |
| 63 | + anagrams.push(start); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + // check right |
| 68 | + if(hashBuild[s[start]] !== undefined) { |
| 69 | + hashBuild[s[start]] = hashBuild[s[start]] + 1; |
| 70 | + if(hashBuild[s[start]] >= 1) { |
| 71 | + countLeft++; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + // slide window |
| 76 | + end++; |
| 77 | + start++; |
| 78 | + } |
| 79 | + |
| 80 | + return anagrams; |
| 81 | +}; |
| 82 | + |
| 83 | +module.exports.findAnagrams = findAnagrams; |
0 commit comments