|
| 1 | +/** |
| 2 | + * 936. Stamping The Sequence |
| 3 | + * https://leetcode.com/problems/stamping-the-sequence/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given two strings stamp and target. Initially, there is a string s of length |
| 7 | + * target.length with all s[i] == '?'. |
| 8 | + * |
| 9 | + * In one turn, you can place stamp over s and replace every letter in the s with the |
| 10 | + * corresponding letter from stamp. |
| 11 | + * |
| 12 | + * For example, if stamp = "abc" and target = "abcba", then s is "?????" initially. |
| 13 | + * In one turn you can: |
| 14 | + * - place stamp at index 0 of s to obtain "abc??", |
| 15 | + * - place stamp at index 1 of s to obtain "?abc?", or |
| 16 | + * - place stamp at index 2 of s to obtain "??abc". |
| 17 | + * |
| 18 | + * Note that stamp must be fully contained in the boundaries of s in order to stamp |
| 19 | + * (i.e., you cannot place stamp at index 3 of s). |
| 20 | + * |
| 21 | + * We want to convert s to target using at most 10 * target.length turns. |
| 22 | + * |
| 23 | + * Return an array of the index of the left-most letter being stamped at each turn. If we |
| 24 | + * cannot obtain target from s within 10 * target.length turns, return an empty array. |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * @param {string} stamp |
| 29 | + * @param {string} target |
| 30 | + * @return {number[]} |
| 31 | + */ |
| 32 | +var movesToStamp = function(stamp, target) { |
| 33 | + const stampLength = stamp.length; |
| 34 | + const targetLength = target.length; |
| 35 | + const moves = []; |
| 36 | + const targetArray = target.split(''); |
| 37 | + let totalReplaced = 0; |
| 38 | + |
| 39 | + function tryStampAt(position) { |
| 40 | + let canStamp = false; |
| 41 | + let hasUnstamped = false; |
| 42 | + |
| 43 | + for (let i = 0; i < stampLength; i++) { |
| 44 | + const currentChar = targetArray[position + i]; |
| 45 | + if (currentChar === '?') continue; |
| 46 | + if (currentChar !== stamp[i]) return false; |
| 47 | + hasUnstamped = true; |
| 48 | + } |
| 49 | + |
| 50 | + if (hasUnstamped) { |
| 51 | + for (let i = 0; i < stampLength; i++) { |
| 52 | + if (targetArray[position + i] !== '?') { |
| 53 | + targetArray[position + i] = '?'; |
| 54 | + totalReplaced++; |
| 55 | + } |
| 56 | + } |
| 57 | + canStamp = true; |
| 58 | + } |
| 59 | + |
| 60 | + return canStamp; |
| 61 | + } |
| 62 | + |
| 63 | + const maxMoves = 10 * targetLength; |
| 64 | + while (moves.length <= maxMoves) { |
| 65 | + let madeChange = false; |
| 66 | + for (let i = 0; i <= targetLength - stampLength; i++) { |
| 67 | + if (tryStampAt(i)) { |
| 68 | + moves.push(i); |
| 69 | + madeChange = true; |
| 70 | + break; |
| 71 | + } |
| 72 | + } |
| 73 | + if (!madeChange) break; |
| 74 | + if (totalReplaced === targetLength) return moves.reverse(); |
| 75 | + } |
| 76 | + |
| 77 | + return []; |
| 78 | +}; |
0 commit comments