ALG/ALG Solve
C++) 백준 2504번 - 괄호의 값
jh2ee
2023. 1. 14. 20:44
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<bits/stdc++.h> | |
using namespace std; | |
int main(){ | |
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); | |
stack<char> s; | |
string in; | |
int cnt=0, num=1; //cnt는 정답, num은 더해질 수 | |
cin>>in; | |
for(int i=0;i<in.length();i++){ | |
//여는 괄호 | |
if(in[i]=='('){ | |
s.push(in[i]); | |
num*=2; //더할 수에 2곱함 | |
} | |
else if(in[i]=='['){ | |
s.push(in[i]); | |
num*=3; //더할 수에 3 곱함 | |
} | |
//닫는 괄호 | |
else if(in[i]==')'){ | |
if(s.empty()||s.top()!='('){ | |
//예외 처리, 비었는데 닫는 괄호 입력 또는 올바르지 않은 순서의 닫는 괄호 입력 | |
cout<<0; return 0; | |
} | |
if(in[i-1]=='(') cnt+=num; //직전 입력이 여는 괄호인 경우 더해준 후 pop | |
s.pop(); num/=2; //직전 입력이 여는 입력이 아니라면 그냥 pop, 여는 과정에서 이미 num에 값을 곱했기 때문 | |
} | |
else if(in[i]==']'){ | |
if(s.empty()||s.top()!='['){ | |
//예외 처리, 비었는데 닫는 괄호 입력 또는 올바르지 않은 순서의 닫는 괄호 입력 | |
cout<<0; return 0; | |
} | |
if(in[i-1]=='[') cnt+=num; //직전 입력이 여는 괄호인 경우 더해준 후 pop | |
s.pop(); num/=3; //직전 입력이 여는 입력이 아니라면 그냥 pop | |
} | |
} | |
if(s.size()!=0) cnt=0; //예외처리, 스택이 비지 않으면 올바른 입력 아님 | |
cout<<cnt; | |
} |