LeetCode: Stamping The Sequence Solution
1/**2 * getAllStampPatterns('abc')3 * => a**, ab*, abc, *b*, *bc, **c4 */5const getAllStampPatterns = stamp => {6 const stampPatterns = new Set() // for O(1) lookup7 const stampN = stamp.length8 for (let i = 0; i < stampN; i++) {9 for (let j = i; j < stampN; j++) {10 stampPatterns.add(11 "?".repeat(i - 0) +12 stamp.substring(i, j + 1) +13 "?".repeat(stampN - 1 - j)14 )15 }16 }17 return stampPatterns18}1920/**21 * @param {string} stamp22 * @param {string} target23 * @return {number[]}24 */25var movesToStamp = function (stamp, target) {26 const targetN = target.length27 const stampN = stamp.length28 const beginningSequence = "?".repeat(targetN)29 const stampPatterns = getAllStampPatterns(stamp)30 const res = []3132 checkIfAllStamped: while (target !== beginningSequence) {33 for (let i = 0; i < targetN - stampN + 1; i++) {34 const substring = target.substring(i, i + stampN)35 if (stampPatterns.has(substring)) {36 target = target.replace(substring, "?".repeat(stampN))37 res.unshift(i)38 continue checkIfAllStamped39 }40 }4142 // break when no pattern is matched43 break44 }4546 // double check47 return target !== beginningSequence ? [] : res48}
Comments
Loading comments...
Tags
leetcode
string
greedy
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
LeetCode: Russian Doll Envelopes
Mar 31, 2021