전형적인 스택문제... 이젠 괄호 얘기만 꺼내도 스택이라고 떠오른다.
크게 어려운 점은 없었고 C++의 경우 띄어쓰기로 input을 나눠받아 일반적인 cin >> 을 사용하면 input 개수가 달라져 한 줄씩 입력받는 getline
함수를 검색해서 알게 되었다.
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
input.pop();
const solution = (sentences) => {
const targets = '()[]';
const answer = sentences.map((sentence) => {
const stack = [];
for (const ch of sentence) {
if (!targets.includes(ch)) continue;
if (ch === '(' || ch === '[') stack.push(ch);
else if (ch === ')') {
if (stack.length === 0 || stack[stack.length - 1] !== '(') return 'no';
stack.pop();
} else if (ch === ']') {
if (stack.length === 0 || stack[stack.length - 1] !== '[') return 'no';
stack.pop();
}
}
if (stack.length !== 0) return 'no';
return 'yes';
});
return answer.join('\n');
};
console.log(solution(input));
#include <bits/stdc++.h>
using namespace std;
string solution(string str) {
stack<char> S;
for (auto ch : str) {
if (ch == '(' || ch == '[') S.push(ch);
else if (ch == ')') {
if (S.empty() || S.top() != '(') return "no";
S.pop();
}
else if (ch == ']') {
if (S.empty() || S.top() != '[') return "no";
S.pop();
}
}
if (!S.empty()) return "no";
return "yes";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
string str;
while(true) {
getline(cin, str);
if (str == ".") break;
cout << solution(str) << '\n';
}
return 0;
}