100win10 2019. 7. 10. 10:42

문제: https://algospot.com/judge/problem/read/BRACKETS2



입력

The first line of the input will contain the number of test cases

C (1C100)
 

Each test is given in a single line as a character string. The strings will only include characters in "[](){}" (quotes for clarity). The length of the string will not exceed 10,000.

출력

For each test case, print a single line "YES" when the formula is well-matched; print "NO" otherwise. (quotes for clarity)



주의할점:

스택이 비어있는 경우와, 마지막에 스택에 남아있는 열린 괄호가 있는지 확인하자


코드 (C ++ ) 종만북 참조


#include <iostream>

#include <string>

#include <stack>

using namespace std;

int C;

bool wellMatched(const string& sentence)

{

stack<char> st;

const string opening("({["), closing(")}]");  // ({[ 와 )}]의 순서를 맞춰준다. find로 인덱스를 맞추어가며 비교하기 때문

for (int i = 0; i < sentence.size(); ++i)

if (opening.find(sentence[i]) != -1) // 0,1,2중 하나가 나왔다면

st.push(sentence[i]); // 스택에 넣어준다.

else

{

if (st.empty()) return false; // 스택이 비어있는 경우는 실패

if(opening.find(st.top()) != closing.find(sentence[i]))  // 스택에 마지막에넣어줬던 인덱스와 비교하여 동일하지 않다면 실패

return false;

st.pop(); // 짝을 맞췄으니 스택에서 뺀다.

}

return st.empty();

}

int main()

{

cin >> C;

while (C--)

{

string sentence;

cin >> sentence;

if (wellMatched(sentence)) {

cout << "YES    " << endl;

}

else

cout << "NO" << endl;

}

return 0;

}