Skip to main content

838.js

/** ------------------------------------------------------------------------------
*
* 838. Push Dominoes
* Topics: Two Pointers, DP
* https://leetcode.com/problems/push-dominoes/description/?envType=daily-question&envId=2025-05-02
*
------------------------------------------------------------------------------ */

/**
* @param {string} dominoes
* @return {string}
*/
var pushDominoes = function (dominoes) {
const len = dominoes.length
let l = -1
let head = "L"
let ans = ""
for (let i = 0; i < len + 1; i++) {
const c = dominoes[i] || ""
if (c === ".") {
if (l === -1) {
l = i
}
} else {
const tail = c || "R"
if (l !== -1) {
const r = i - 1
const count = r - l + 1
// console.log(l, i - 1, head, tail)
if (head === "L" && tail === "L") {
ans += "L".repeat(count)
} else if (head === "R" && tail === "R") {
ans += "R".repeat(count)
} else if (head === "L" && tail === "R") {
ans += ".".repeat(count)
} else {
ans += "R".repeat(count / 2)
if (count % 2) {
ans += "."
}
ans += "L".repeat(count / 2)
}
}
ans += c
head = c
l = -1
}
}
return ans
}

console.log(pushDominoes("RR.L"))