LeetCode-32. 最长有效括号(Longest Valid Parentheses)

class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> st;
        int ans = 0;
        if(s.size() <= 1) return 0;
        st.push(-1);
        for (int i = 0; i < s.size(); ++i)
        {
        	if(s[i] == '(') {
        		st.push(i);
        	}else{
        		st.pop();
        		if(st.empty()){//更新断点
        			st.push(i);
        		}else{//更新最长子串
        			ans = max(ans, i - st.top());
        		}
        	}
        }
        return ans;
    }
};

题目链接:https://leetcode-cn.com/problems/longest-valid-parentheses/

发布了42 篇原创文章 · 获赞 2 · 访问量 1400

猜你喜欢

转载自blog.csdn.net/Listen_heart/article/details/103196447