题解 | #最长的括号子串#
最长公共前缀
http://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
栈
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;
}
};