之前字符串的题有:
BM44 有效括号序列
用栈的方法
BM60 括号生成
用递归的方法
模板的:
模板没有用到动态规划,更像一种循环遍历。代码中的细节处理很巧妙。
栈专门用于储存左括号的位置。
比如例子"s=(()()"
s[2]把栈中[0,1]的1消掉,s[4]把栈中[0,3]的3消掉,栈中多余的左括号中最top是0,4-0=4即为所求。
我的误区,以为s[4]把[0,1]的1消掉。所以先i-st.top()+1=4,再st.pop()。其实是不对的。
在正确连续括号后,左右括号太多,不需要管。
在正确连续括号前(包括两个正确连续括号中间):
- 左括号太多,有st.pop()+max(res,i-st.top())
- 右括号太多,有start记录+max(res,i-start)
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
int longestValidParentheses(string s) {
// write code here
int res = 0;
int start = -1;
stack<int> st;
for(int i = 0; i < s.length(); i++){
if(s[i] == '(')
st.push(i);
else{
//多余的右括号,中断了连续括号的可能
if(st.empty()){
start = i;
}
else{
st.pop();
if(st.empty())
res = max(res, i-start);
else
res = max(res, i-st.top()); //巧妙
}
}
}
return res;
}
};