|
| 1 | +/** |
| 2 | + * 838. Push Dominoes |
| 3 | + * https://leetcode.com/problems/push-dominoes/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There are n dominoes in a line, and we place each domino vertically upright. In the beginning, |
| 7 | + * we simultaneously push some of the dominoes either to the left or to the right. |
| 8 | + * |
| 9 | + * After each second, each domino that is falling to the left pushes the adjacent domino on the |
| 10 | + * left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on |
| 11 | + * the right. |
| 12 | + * |
| 13 | + * When a vertical domino has dominoes falling on it from both sides, it stays still due to the |
| 14 | + * balance of the forces. |
| 15 | + * |
| 16 | + * For the purposes of this question, we will consider that a falling domino expends no additional |
| 17 | + * force to a falling or already fallen domino. |
| 18 | + * |
| 19 | + * You are given a string dominoes representing the initial state where: |
| 20 | + * - dominoes[i] = 'L', if the ith domino has been pushed to the left, |
| 21 | + * - dominoes[i] = 'R', if the ith domino has been pushed to the right, and |
| 22 | + * - dominoes[i] = '.', if the ith domino has not been pushed. |
| 23 | + * |
| 24 | + * Return a string representing the final state. |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * @param {string} dominoes |
| 29 | + * @return {string} |
| 30 | + */ |
| 31 | +var pushDominoes = function(dominoes) { |
| 32 | + const forces = new Array(dominoes.length).fill(0); |
| 33 | + |
| 34 | + let force = 0; |
| 35 | + for (let i = 0; i < dominoes.length; i++) { |
| 36 | + if (dominoes[i] === 'R') { |
| 37 | + force = dominoes.length; |
| 38 | + } else if (dominoes[i] === 'L') { |
| 39 | + force = 0; |
| 40 | + } else { |
| 41 | + force = Math.max(force - 1, 0); |
| 42 | + } |
| 43 | + forces[i] += force; |
| 44 | + } |
| 45 | + |
| 46 | + force = 0; |
| 47 | + for (let i = dominoes.length - 1; i >= 0; i--) { |
| 48 | + if (dominoes[i] === 'L') { |
| 49 | + force = dominoes.length; |
| 50 | + } else if (dominoes[i] === 'R') { |
| 51 | + force = 0; |
| 52 | + } else { |
| 53 | + force = Math.max(force - 1, 0); |
| 54 | + } |
| 55 | + forces[i] -= force; |
| 56 | + } |
| 57 | + |
| 58 | + return forces.map(f => { |
| 59 | + if (f > 0) return 'R'; |
| 60 | + if (f < 0) return 'L'; |
| 61 | + return '.'; |
| 62 | + }).join(''); |
| 63 | +}; |
0 commit comments