백준 - 단계별로 풀어보기 [4949]
https://www.acmicpc.net/problem/4949
풀이
자료구조에서 스택의 기본적인 괄호 예제입니다.
입력받은 문자열에서 괄호만 찾아서 짝이 맞는지 확인 후 출력하는 간단한 문제입니다.
Code
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
while (true)
{
stack<char> _stack;
bool result = true;
string s;
getline(cin, s);
if (s[0] == '.')
break;
// 마지막 글자는 . 이니까 - 1
for (int i = 0; i < s.length() - 1; i++)
{
if (s[i] == '(') _stack.push(s[i]);
if (s[i] == '[') _stack.push(s[i]);
/*
* 닫는 괄호가 나오지만, stack에 여는 괄호가 없을경우 false
* 스택에 쌓인 가장 위 데이터가 짝이 안맞으면 false
*/
if (s[i] == ')')
{
if (_stack.empty() || _stack.top() == '[') result = false;
else _stack.pop();
}
if (s[i] == ']')
{
if (_stack.empty() || _stack.top() == '(') result = false;
else _stack.pop();
}
}
if (_stack.empty() && result) cout << "yes" << endl;
else cout << "no" << endl;
}
}
'💻 OnlineJudge > Baekjoon' 카테고리의 다른 글
[백준 / BOJ] C++ 2164 카드 2 (0) | 2022.08.22 |
---|---|
[백준 / BOJ] C++ 18258 큐 2 (0) | 2022.08.19 |
[백준 / BOJ] C++ 9012 괄호 (0) | 2022.08.17 |
[백준 / BOJ] C++ 10773 제로 (0) | 2022.08.16 |
[백준 / BOJ] C++ 24416 피보나치 수열 1 (0) | 2022.08.03 |