LeetCode: Permutation in String Solution
Notice the constraintsApproach
Notice that there's a constraint "s1 and s2 consist of lowercase English letters"
Maintain a sliding window with size of s1.length
Use a counter base on character occurences to detect for permutation
Question now turns to "check if two strings are permutation of each other"
Implementation
1var checkInclusion = function (s1, s2) {2 let [n1, n2] = [s1.length, s2.length]3 let occurences = Array(26).fill(0)45 const mutate = (charCode, dir) =>6 (occurences[charCode - "a".charCodeAt(0)] += dir)78 const isMatch = () => occurences.every(x => x === 0)910 for (let i = 0; i < n1; i++) {11 mutate(s1.charCodeAt(i), +1)12 }1314 for (let i = 0; i < n2; i++) {15 mutate(s2.charCodeAt(i), -1)16 if (i - n1 >= 0) mutate(s2.charCodeAt(i - n1), +1)1718 if (isMatch()) return true19 }2021 return false22}
Comments
Loading comments...
Tags
leetcode
string
hash table
sliding window
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
Sliding window uses two pointers?
Previous Post
Several ways