[백준] 괄호 #9012

welchs·2022년 1월 5일
0

알고리즘

목록 보기
3/44
post-thumbnail

설명

전형적인 stack을 이용해서 푸는 문제
'('일 때는 스택에 쌓고 ')'일 때는 stack에서 빼서 올바른 괄호 쌍인지 판단하면 된다.
JS풀이는 이전에 푼 문제에서 Stack 클래스를 구현해놔서 구현한김에 굳이 Stack class를 복붙해서 가져와서 '('를 stack에 push하는 방식으로 구현했지만 올바른지 판단하기 위해서는 그냥 정수 변수 하나 두고 '('면 +1, ')'면 -1 해주고 결과가 0인지 판단하는게 더 쉽다.(그래서 C++은 그렇게 풀었다.)

Node.js 풀이

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');

const N = Number(input[0]);
const inputs = input.slice(1);

class Stack {
  constructor() {
    this.stack = [];
  }

  push(value) {
    this.stack.push(value);
  }
  pop() {
    if (this.size() === 0) return -1;
    return this.stack.pop();
  }
  top() {
    return this.size() ? this.stack[this.size() - 1] : -1;
  }
  size() {
    return this.stack.length;
  }
  empty() {
    return this.size() === 0 ? 1 : 0;
  }
}

const solution = (N, inputs) => {
  const answer = inputs.map((input) => {
    const stack = new Stack();
    for (const ch of input) {
      if (ch === '(') stack.push('(');
      else {
        if (stack.top() === '(') stack.pop();
        else return 'NO';
      }
    }
    return stack.size() === 0 ? 'YES' : 'NO';
  });
  return answer.join('\n');
};

console.log(solution(N, inputs));

C++ 풀이

#include <bits/stdc++.h>
using namespace std;

bool isValid(string s) {
    int n = s.length();
    int cnt = 0;
    for (auto ch : s) {
        if (ch == '(') cnt++;
        else {
            if (cnt == 0) return false;
            else cnt--;
        }
    }
    return cnt == 0;
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int N;
    cin >> N;
    string s;
    for (int i=0; i<N; i++) {
        cin >> s;
        if (isValid(s)) cout << "YES\n";
        else cout << "NO\n";
    }

    return 0;
}
profile
고수가 되고 싶은 조빱

0개의 댓글