[백준] 좋은 단어 #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;
}
Author And Source
이 문제에 관하여([백준] 좋은 단어 #3986), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@ahu8867/백준-좋은-단어-3986저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)