12. 最大括号深度

108 阅读1分钟

题目描述

现有一字符串仅由 ‘(‘,’)’,'{‘,’}’,'[‘,’]’六种括号组成。

若字符串满足以下条件之一,则为无效字符串:

①任一类型的左右括号数量不相等;

②存在未按正确顺序(先左后右)闭合的括号。

输出括号的最大嵌套深度,若字符串无效则输出0。

0≤字符串长度≤100000

输入描述

一个只包括 ‘(‘,’)’,'{‘,’}’,'[‘,’]’的字符串

输出描述

一个整数,最大的括号深度

用例

输入[]
输出1
说明有效字符串,最大嵌套深度为1
输入([]{()})
输出3
说明有效字符串,最大嵌套深度为3
输入(]
输出0
说明无效字符串,有两种类型的左右括号数量不相等
输入([)]
输出0
说明无效字符串,存在未按正确顺序闭合的括号
输入)(
输出0
说明无效字符串,存在未按正确顺序闭合的括号。

C++源码

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

int main()
{
    string str;
    cin >> str;
    int maxDepth = 0;
    stack<char>st;
    for (int i = 0 ; i < str.size(); i++) {
        if (str[i] == '(') {
            st.push(')');
        }
        else if (str[i] == '[') {
            st.push(']');
        }
        else if (str[i] == '{') {
            st.push('}');
        } else {
            maxDepth = max(maxDepth, (int) st.size());
            if (!st.empty() && str[i] == st.top()) {
                st.pop();
            } else {
                cout << 0 << endl;
                return 0;
            }
        }
    }
    if (st.size() != 0) {
        cout << 0 << endl;
        return 0;
    }
    cout << maxDepth << endl;
    return 0;
}