leetcode+ 括号匹配的最大长度

点击打开链接
//需要借助变量l记录当前括号匹配的子串的左侧位置
class Solution {
public:
    int longestValidParentheses(string s) {
        int res =0, l=0;
        stack<int> st;
        for(int i=0; i<s.size(); i++){
            if(s[i]=='(') st.push(i);
            else{
                if(st.empty()) l = i+1;
                else{
                    st.pop();
                    if(st.empty()) res = max(res, i-l+1);
                    else
                        res = max(res, i-st.top());
                }
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/u013554860/article/details/81047110