๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ป ์ฝ”๋”ฉํ…Œ์ŠคํŠธ/๋ฐฑ์ค€

[๋ฐฑ์ค€/Python, Node.js] ๊ด„ํ˜ธ - ์ž๋ฃŒ๊ตฌ์กฐ Stack

by ๋ฝ€์งœ๊ผฌ 2025. 3. 27.
728x90
๋ฐ˜์‘ํ˜•

https://www.acmicpc.net/problem/9012

 

ํŒŒ์ด์ฌ

# ๋ฐฑ์ค€ 9012 - ๊ด„ํ˜ธ

T = int(input())
result = []

for i in range(T):
    isVPS = input()
    left = isVPS.count('(')
    right = isVPS.count(')')

    if left == right:
        result.append("YES")
    else:
        result.append("NO")

for r in result:
    print(r)

 

๊ทธ๋ƒฅ count๋กœ ๋น„๊ตํ•ด์„œ ()๊ฐœ์ˆ˜๊ฐ€ ๋‹ค๋ฅด๋ฉด ํ‹€๋ฆฐ๊ฒŒ ์•„๋‹Œ๊ฐ€? ์ƒ๊ฐํ–ˆ๋Š”๋ฐ

์ˆœ์„œ๋ฅผ ๊ณ ๋ คํ•˜์ง€ ์•Š์•˜๋‹ค.

 

์ˆœ์„œ๋ฅผ ๊ณ ๋ คํ•˜๋ ค๋ฉด Stack ์„ ์จ์•ผํ•œ๋‹ค.

 

์Šคํƒ


๋‚˜์ค‘์— ๋„ฃ์€ ๊ฒƒ์ด ๋จผ์ € ๋‚˜์˜ค๋Š”(LIFO, Last In First Out) ๊ตฌ์กฐ

 

T = int(input())

for i in range(T):
    stack = []
    isVPS = input()

    for c in isVPS:
        if c == '(':
            stack.append(c)
        elif c == ')':
            if len(stack) == 0:
                stack.append(c)
                break
            else:
                stack.pop()
    
    if len(stack) !=0:
        print("NO")
    else:
        print("YES")

 

 


์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ

const input = require("fs")
  .readFileSync(process.platform === "linux" ? "/dev/stdin" : "./input.txt")
  .toString()
  .trim()
  .split("\n")

const T = Number(input[0]);

for (let i = 1; i <= T; i++) {
  const line = input[i];
  const stack = [];

  for (const c of line){
    if (c == '(') {
      stack.push(c);
    } else if (c == ')') {
      if (stack.length == 0){
        stack.push(c);
        break;
      }
      else{ stack.pop();}
    }
  }

  if (stack.length != 0){
    console.log("NO")
  }else{
    console.log("YES")
  }
}
728x90
๋ฐ˜์‘ํ˜•