Created
February 12, 2022 05:30
-
-
Save drewkiimon/ba5bcc95a1811d32fe75f8ffd1bacc7b to your computer and use it in GitHub Desktop.
Leetcode Permutation in String problem 567
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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. | |
*/ | |
const checkInclusion = (s1, s2) => { | |
if (s1.length > s2.length) return false; | |
const s1Dict = {}; | |
const s2Dict = {}; | |
// Create dictionary of s1 | |
for (let i = 0; i <= s1.length - 1; i++) { | |
let letter = s1[i]; | |
let letter2 = s2[i]; | |
s1Dict[letter] = letter in s1Dict ? s1Dict[letter] + 1 : 1; | |
s2Dict[letter2] = letter2 in s2Dict ? s2Dict[letter2] + 1 : 1; | |
} | |
if (objectsAreEqual(s1Dict, s2Dict)) return true; | |
for (let i = s1.length; i <= s2.length - 1; i++) { | |
// Remove letter from s2 | |
let letter = s2[i - s1.length]; | |
s2Dict[letter]--; | |
let newLetter = s2[i]; | |
s2Dict[newLetter] = newLetter in s2Dict ? s2Dict[newLetter] + 1 : 1; | |
if (objectsAreEqual(s1Dict, s2Dict)) return true; | |
} | |
return false; | |
}; | |
const objectsAreEqual = (a, b) => { | |
const keys = Object.keys(a); | |
for (let i = 0; i <= keys.length - 1; i++) { | |
let key = keys[i]; | |
if (a[key] !== b[key]) return false; | |
} | |
return true; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment