코딩테스트

서투른 암소(c++) - stack

leeeehhjj 2024. 2. 25. 18:11

https://aronglife.tistory.com/entry/AlgorithmString-서투른-암소균형잡힌-괄호-문자열

 

[Algorithm][String] 균형 잡힌 괄호 문자열1

순서 I. 문제 II. 접근 III. 구현 I. 문제 균형 잡힌 문자열이 될 수 있도록 뒤집어야 하는 (예를들어, 오른쪽 괄호를 왼쪽 괄호로, 또는 왼쪽 괄호를 오른쪽 괄호로 변경) 괄호 문자의 최소 수를 계

aronglife.tistory.com

#include <iostream>
#include <stack>
using namespace std;

char str[100000+10];
stack<char> st;
void InputData(){
    cin >> str;
}

int solve() {
    int cnt = 0;
    for (int i=0; str[i]; i++) {
        if (str[i] == '(') st.push('(');
        else {
            if (!st.empty() && st.top() == '(') {
                st.pop();
            }
            else {
                st.push('(');
                cnt++;
            }
        }
    }
    
    cnt += st.size()/2;
    
    return cnt;
}

int main(){
    int ans = -1;

    InputData();// 입력받는 부분

    // 여기서부터 작성
    ans = solve();

    cout << ans << endl;// 출력하는 부분
    return 0;
}