Permutation in String
Problem statement
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
In other words, return true if one of s1's permutations is the substring of s2.
Example 1:
Input: s1 = "ab", s2 = "eidbaooo"Output: trueExplanation: s2 contains one permutation of s1 ("ba").Example 2:
Input: s1 = "ab", s2 = "eidboaoo"Output: false
Constraints:
1 <= s1.length, s2.length <= 104s1ands2consist of lowercase English letters.
My solution
/**
* @param {string} s1
* @param {string} s2
* @return {boolean}
*/
var checkInclusion = function(s1, s2) {
const patternMap = new Map();
const stringMap = new Map();
for (let i = 0; i < s1.length; i++) {
const s1Char = s1.charAt(i)
const s2Char = s2.charAt(i)
patternMap.set(s1Char, (patternMap.get(s1Char) || 0) + 1)
stringMap.set(s2Char, (stringMap.get(s2Char) || 0) + 1)
}
let left = 0;
let right = s1.length - 1;
while (right < s2.length) {
if (isEqual(patternMap, stringMap)) {
return true;
}
const firstCharInStr2 = s2.charAt(left);
if (stringMap.get(firstCharInStr2) > 1) {
stringMap.set(firstCharInStr2, stringMap.get(firstCharInStr2) - 1)
} else {
stringMap.delete(firstCharInStr2)
}
left++;
right++;
const lastCharOfStr2 = s2.charAt(right)
stringMap.set(lastCharOfStr2, (stringMap.get(lastCharOfStr2) || 0) + 1)
}
return false;
};
function isEqual(map1, map2) {
if (map1.size !== map2.size) {
return false;
}
for (const key of map1.keys()) {
if (!map2.get(key) || map1.get(key) !== map2.get(key)) {
return false;
}
}
return true;
}