|
| 1 | +/** |
| 2 | + * 2337. Move Pieces to Obtain a String |
| 3 | + * https://leetcode.com/problems/move-pieces-to-obtain-a-string/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given two strings start and target, both of length n. Each string consists only of |
| 7 | + * the characters 'L', 'R', and '_' where: |
| 8 | + * - The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if |
| 9 | + * there is a blank space directly to its left, and a piece 'R' can move to the right only if |
| 10 | + * there is a blank space directly to its right. |
| 11 | + * - The character '_' represents a blank space that can be occupied by any of the 'L' or 'R' |
| 12 | + * pieces. |
| 13 | + * |
| 14 | + * Return true if it is possible to obtain the string target by moving the pieces of the string |
| 15 | + * start any number of times. Otherwise, return false. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {string} start |
| 20 | + * @param {string} target |
| 21 | + * @return {boolean} |
| 22 | + */ |
| 23 | +var canChange = function(start, target) { |
| 24 | + const pieces = []; |
| 25 | + const targetPieces = []; |
| 26 | + |
| 27 | + for (let i = 0; i < start.length; i++) { |
| 28 | + if (start[i] !== '_') pieces.push([start[i], i]); |
| 29 | + if (target[i] !== '_') targetPieces.push([target[i], i]); |
| 30 | + } |
| 31 | + |
| 32 | + if (pieces.length !== targetPieces.length) return false; |
| 33 | + |
| 34 | + for (let i = 0; i < pieces.length; i++) { |
| 35 | + if (pieces[i][0] !== targetPieces[i][0]) return false; |
| 36 | + if (pieces[i][0] === 'L' && pieces[i][1] < targetPieces[i][1]) return false; |
| 37 | + if (pieces[i][0] === 'R' && pieces[i][1] > targetPieces[i][1]) return false; |
| 38 | + } |
| 39 | + |
| 40 | + return true; |
| 41 | +}; |
0 commit comments