[백준] 좋은 단어 #3986

13924 단어 3986백준3986

설명

처음에 문제 이해를 못했는데 문제를 이해하면 바로 풀리는 문제
A끼리 괄호쌍, B끼리 괄호쌍이라고 생각하고 풀면 된다.
문제말대로 문자 각자 위에 선을 그은 후에 같은 문자쌍끼리 선이 겹치지 않고 묶이는지 확인하면 된다. -> 이게 괄호쌍 문제랑 동일하다.

Node.js 풀이

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

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

const solution = (N, words) => {
  let answer = 0;
  for (const word of words) {
    const stack = [];
    for (const ch of word) {
      if (stack.length === 0) {
        stack.push(ch);
        continue;
      }
      if (ch === 'A') {
        if (stack[stack.length - 1] === 'A') {
          stack.pop();
        } else {
          stack.push(ch);
        }
      } else if (ch === 'B') {
        if (stack[stack.length - 1] === 'B') {
          stack.pop();
        } else {
          stack.push(ch);
        }
      }
    }
    if (stack.length === 0) answer += 1;
  }
  return answer;
};

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

C++ 풀이

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

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int N; cin >> N;
    int cnt = 0;
    while(N--) {
        string str; cin >> str;
        stack<char> S;
        for (auto ch : str) {
            if (S.empty()) {
                S.push(ch);
                continue;
            }
            if (ch == 'A') {
                if (S.top() == 'A') S.pop();
                else S.push(ch);
            }
            else if (ch == 'B') {
                if (S.top() == 'B') S.pop();
                else S.push(ch);
            }
        }
        if (S.empty()) cnt += 1;
    }
    cout << cnt << '\n';
    return 0;
}

좋은 웹페이지 즐겨찾기