[JS] Find All Anagrams in a String
2022. 8. 8. 19:22
🔒 문제 (LeetCode 438)
Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Constraints:
- 1 <= s.length, p.length <= 3 * 104
- s and p consist of lowercase English letters.
🌊 입출력
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".
🔑 해결
🌌 알고리즘 - sliding window
/**
* @param {string} s
* @param {string} p
* @return {number[]}
*/
var findAnagrams = function(s, p) {
const result = [];
let countChars = {};
for(let char of p) {
if(char in countChars) {
countChars[char]++;
} else countChars[char] = 1;
}
let l = 0;
let r = 0;
let count = p.length;
while(r < s.length) {
if(countChars[s[r]] > 0) count--;
countChars[s[r]]--;
r++;
if(count === 0) result.push(l);
if(r - l === p.length) {
if(countChars[s[l]] >= 0) count++;
countChars[s[l]]++;
l++;
}
}
return result;
};
'코딩테스트 (JS) > 투포인터' 카테고리의 다른 글
[JS] Minimum Size Subarray Sum (0) | 2022.08.08 |
---|---|
[JS] Subarray Product Less Than K (0) | 2022.08.08 |
[JS] Container With Most Water (0) | 2022.08.07 |
[JS] Interval List Intersections (0) | 2022.08.07 |
[JS] 3Sum (0) | 2022.08.06 |