给定一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长的包含有效括号的子串的长度。
示例 1:
输入: “(()” 输出: 2 解释: 最长有效括号子串为 “()” 示例 2:
输入: “)()())” 输出: 4 解释: 最长有效括号子串为 “()()”
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-valid-parentheses 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution { public: int longestValidParentheses(string s) { int res = 0; stack<pair<char,int>>st; int id=0; st.push(make_pair<char,int>('F',0)); for(auto c:s){ ++id; if(c=='('){ st.push(make_pair('(',id)); }else{ pair<char,int> p = st.top(); if(p.first=='('){ st.pop(); res = max(res,id-st.top().second); }else{ if(p.first=='F'){ st.top().second=id; } // assert(p.first=='F'); // st.top().second=id; } } } return res; } };