求最长有效括号子串的长度

#include
#include
#include
using namespace std;

int main()
{
    string str;
    getline(cin, str);
    int max = 0;
    stack st;

    int length = str.length();
    
    for (int i = 0; i < length; i++)
    {
        if (')'== str[i] && '(' == str[st.top()] && !st.empty())
        {
            st.pop();
            if (st.empty())
            {
                max = i + 1;
            }
            else if (i-st.top()>max)
            {
                max = i - st.top();
            }
        }
        else
        {
            st.push(i); //左括号入栈
        }
    }
    cout << max << endl;
    return 0;

}

你可能感兴趣的:(求最长有效括号子串的长度)