题目
代码
function getMinElectricBoxes(input_str) {
const n = input_str.length;
const powerBoxPositions = [];
let lastPowerBoxUsed = false;
for (let i = 0; i < n; i++) {
if (input_str.charAt(i) === "M") {
if (
i - 1 >= 0 &&
input_str.charAt(i - 1) === "M" &&
i + 1 < n &&
input_str.charAt(i + 1) === "M"
) {
return -1;
}
if (
(i - 1 === 0 && input_str.charAt(i - 1) === "M") ||
(i + 1 === n && input_str.charAt(i - 1) === "M")
) {
return -1;
}
const pos_left = Math.max(0, i - 1);
const pos_right = Math.min(n - 1, i + 1);
if (powerBoxPositions.length > 0 && !lastPowerBoxUsed) {
if (powerBoxPositions[powerBoxPositions.length - 1] === pos_left) {
powerBoxPositions.pop();
lastPowerBoxUsed = true;
}
} else {
lastPowerBoxUsed = false;
}
powerBoxPositions.push(pos_right);
}
}
return powerBoxPositions.length;
}
//测试样例
console.log(getMinElectricBoxes("MIIM"));