NC49 最长的括号子串
最长的括号子串
https://www.nowcoder.com/practice/45fd68024a4c4e97a8d6c45fc61dc6ad?tpId=196&tqId=37079&rp=1&ru=/exam/oj&qru=/exam/oj&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26pageSize%3D50%26search%3D%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D196&difficulty=undefined&judgeStatus=undefined&tags=581&title=
class Solution {
public:
int longestValidParentheses(string s) {
int start=-1;
int ans=0;
stack<int> stack1;
int n=s.size();
//遍历整个字符串
//如果是左括号就将其入栈
//如果是右括号,先判断一下当前栈是否为空,如果栈为空,就表示不符合合法的括号序列,将start更新为当前位置i
//如果栈不为空,就将栈顶元素出栈,之后再判断一下
//如果栈不位空,就表示右括号不够,无法将前面的左括号全部匹配 i-stack1.top()
//否则即表示能全部匹配 i-start
for(int i=0;i<n;i++){
if(s[i]=='('){
stack1.push(i);
}else{
if(stack1.empty()){
start=i;
}else{
stack1.pop();
if(!stack1.empty()){
ans=max(ans,i-stack1.top());
}else{
ans=max(ans,i-start);
}
}
}
}
return ans;
}
};