栈
class Solution {
public:
/**
*
* @param s string字符串
* @return int整型
*/
int longestValidParentheses(string s) {
// write code here
int n = s.length();
stack<int> stk;
stk.push(-1); //最后一次未匹配的右括号
int ans = 0;
for(int i = 0; i < n; i ++){
if(s[i] == '(') stk.push(i);
else{
stk.pop();
if(stk.empty()) stk.push(i); //未匹配的右括号
else{
ans = max(ans, i - stk.top());
}
}
}
return ans;
}
}; 
京公网安备 11010502036488号