C++)
#include <iostream>
#include <stack>
using namespace std;
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int tc;
cin >> tc;
string temp;
while (tc--) {
cin >> temp;
stack<char> st;
bool flag = false;
for (auto ele : temp) {
// 여는 괄호이면 무조건 push
if (ele == '(')
st.push(ele);
// 닫는 괄호이면서 스택의 top이 '('이면 짝이니까 pop
else if (ele == ')' && !st.empty() && st.top() == '(')
st.pop();
// 그 외는 짝이 무조건 안 맞는 경우이므로 더 검사할 필요가 없다
else {
flag = true;
break;
}
}
if (flag || !st.empty())
cout << "NO\n";
else
cout << "YES\n";
}
return 0;
}
Python)
import sys
read = sys.stdin.readline
tc = int(read().rstrip())
for _ in range(tc):
st = read().rstrip()
li = []
flag = False
for x in st:
if x == '(':
li.append(x)
elif x == ')' and li and li[-1] == '(':
li.pop()
else:
flag = True
break
print("NO" if flag or li else "YES")'백준 1 > 자료구조' 카테고리의 다른 글
| [백준 1158] 요세푸스 문제 (C++/Python) (0) | 2020.12.06 |
|---|---|
| [백준 2161] 카드1 (C++/Python) (0) | 2020.12.06 |
| [백준 10845] 큐 (C++/Python) (0) | 2020.12.06 |
| [백준 10828] 스택 (C++/Python) (0) | 2020.12.06 |
| [백준 10773] 제로 (C++/Python) (0) | 2020.12.06 |