// IN
So when I die (the [first] I will see in (heaven) is a score list).
[ first in ] ( first out ).
Half Moon tonight (At least it is better than no Moon at all].
A rope may form )( a trail in a maze.
Help( I[m being held prisoner in a fortune cookie factory)].
([ (([( [ ] ) ( ) (( ))] )) ]).
. // 알파벳, 공백, 소괄호, 대괄호, 마지막 온점 (1 <= 길이 <= 100)
. // 입력 끝
// OUT
yes // 문자열 내 괄호가 균형잡혔는가?
yes
no
no
no
yes
yes
C++ 풀이
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
while (true)
{
string s;
getline(cin, s);
if (s == ".")
break;
stack<char> st;
bool isBalanced = true;
for (auto c: s)
{
if ((c == '(') || (c == '['))
{
st.push(c);
}
else if ((c == ')') || (c == ']'))
{
if (st.empty() || (abs(c - st.top()) > 2))
{
isBalanced = false;
break;
}
st.pop();
}
}
if (st.empty() == false)
isBalanced = false;
cout << (isBalanced ? "yes": "no") << '\n';
}
}
메모
)와 ] 입력받고 처리하는 부분 모양이 비슷해서 어떻게 합칠 수 있을까 고민
아스키코드 표를 보고 (와 ), [와 ] 수 차이가 각각 1, 2인 것을 보고, diff <= 2로 괄호쌍 여부을 판단