0
0

More than 1 year has passed since last update.

paizaラーニング レベルアップ問題集 スタック・キューメニュー JavaScript 括弧列

Posted at

括弧列 (paizaランク C 相当)

解答例

stackに"("をためる。")"が来たら、正しい括弧か判定する。スタックの末尾が"("なら正しい括弧列になるので、stackから末尾の"("を取り除く。最後にstackが空なら正しい括弧列。

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");

const [N] = lines[0].split(" ").map(Number);
const S = lines[1].split("");//記号があるので文字列

let stack = [];
//Sを調べていく
for (let i = 0; i < N; i++) {
  if (S[i] === "(") {
    stack.push("(");
  } else {
    if (stack[stack.length - 1] === "(") { //正しい括弧列か判定
      stack.pop();
    }
  }
}

//スタックが空ならば正しい括弧
console.log(stack.length === 0 ? "Yes" : "No");
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0