본문 바로가기
Programming/Algorithm

백준 스택 괄호

by OKOK 2018. 1. 29.

#include <iostream>

#include <stack>

#include <string>


using namespace std;


bool Check(string str) {

int len = (int)str.length();

stack<char> st;


for (int i = 0; i < len; i++) {

char c = str[i];


if (c == '(') {

st.push(str[i]);

}

else {

if (!st.empty()) {

st.pop();

}

else {

return false;

}

}

}


return st.empty();

}


int main(void) {

int n;

cin >> n;

for (int i = 0; i < n; i++) {

string str;

cin >> str;


if (Check(str)) {

cout << "YES" << endl;

}

else {

cout << "NO" << endl;

}

}


return 0;


스택 명령어 몇개만 알면 구현 문제이다. 그러나 여기서 내가 착각한것은 ((())) 괄호를 받을때, 하나씩 받는 것이 아니라, 전체적으로 하나를 받고 그것을 하나씩 접근했어야 한다는 점이다. 이것은 string 을 아직 익숙하게 접하지 못했다는 뜻이다. string 으로 받고 그것을 lenth 를 사용햇 하나씩 접근 하도록 합니다. 오케이요. length 랑 사이즈랑 같을텐데, 의심적으면 하나를 받고 이것을 출력해서 확인해보도록 합니다.