https://www.acmicpc.net/problem/4889
4889번: 안정적인 문자열
입력은 여러 개의 데이터 세트로 이루어져 있다. 각 데이터 세트는 한 줄로 이루어져 있다. 줄에는 여는 괄호와 닫는 괄호만으로 이루어진 문자열이 주어진다. 문자열의 길이가 2000을 넘는 경우
www.acmicpc.net
스택을 이용해서 올바른 문자열인지 확인할 수 있는지에 관한 문제다.
'{'는 그대로 스택에 넣어주면 되고,
'}'의 경우를 생각해야한다.
1) 스택이 비어있는 경우엔 '{'으로 바꿔넣어야한다.
2) '{'가 스택의 top에 있는 경우(스택의 top에 '}'는 있을 수 없다), pop해준다.
#include <iostream>
#define fio cin.tie(0)->sync_with_stdio(0)
using namespace std;
#include <stack>
#include <string>
int main(){
fio;
int TC = 1;
while(1){
string S; cin >> S;
//종료조건 확인
bool flg = true;
for(int i=0; i < S.size(); i++){
if(S[i] == '-'){
flg = false;
break;
}
}
if(!flg) break;
//---------
stack<char> stack_;
int change_cnt = 0;
int need_cnt = 0;
for(int i=0; i<S.size(); i++){
char now = S[i];
if(now == '{'){
need_cnt++;
stack_.push(now);
}else{// }
if(stack_.empty()){
change_cnt++;
need_cnt++;
stack_.push('{');
}else{
//if(stack_.top() == '{'){
need_cnt--;
stack_.pop();
//}
}
}
}
change_cnt += (need_cnt)/2;
cout << TC <<". " << change_cnt <<'\n';
//
TC++;
}
return 0;
}
'알고리즘 > 백준' 카테고리의 다른 글
백준 2841 외계인의 기타 연주 (0) | 2021.12.26 |
---|---|
백준 5964 Best Parenthesis (0) | 2021.12.26 |
백준 2504 괄호의 값 (0) | 2021.12.25 |
백준 1662 압축 (0) | 2021.12.25 |
백준 14713 앵무새 (0) | 2021.12.24 |