问题描述:
给定一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长的包含有效括号的子串的长度。
示例 1:
输入: “(()”
输出: 2
解释: 最长有效括号子串为 “()”
示例 2:
输入: “)()())”
输出: 4
解释: 最长有效括号子串为 “()()”
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-valid-parentheses
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st;
vector<bool> mark(s.length(),0);
int len=0,res=0;
for(int i=0;i<s.length();i++){
if(s[i]=='(') st.push(i);
else{
if(st.empty()) mark[i]=1;
else st.pop();
}
}
while(!st.empty()){
mark[st.top()]=1;
st.pop();
}
for(int i=0;i<s.length();i++){//寻找长度最长的0
if(mark[i]){
len=0;
continue;
}
len++;
res=max(res,len);
}
return res;
}
};