给定一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长的包含有效括号的子串的长度。
示例 1:
输入: "(()" 输出: 2 解释: 最长有效括号子串为 "()"示例 2:
输入: ")()())" 输出: 4 解释: 最长有效括号子串为 "()()"stack:
class Solution { public: int longestValidParentheses(string s) { stack<int> st; int count = 0; int max = 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{ max = max > i-st.top()? max:i-st.top(); } } } return max; } };