思路:搜索字符串,碰到 '(' 就压入栈中,并记录其位置,碰到 ')' 就从栈顶取出一个符号'(',并且更新当前的最大合理括号对数目。令f(i)为当前的数目,则f(i) = f(i - pre) + i - pre;
其中pre表示从栈顶取出的'('符号位置的前一个位置,即当前如果搜索到')'(位置为pre + 1),找出与它配对的'(',它们之间的合理数目为 i - pre,加上前面位置pre已有的合理数目,就是整个合理数目。注意,如果碰到第i个位置的符号是‘(’,则让f(i) = 0,因为 '(' 总是不能形成合理括号对。
struct Symbol{
char sym;
int position;
Symbol(char a,int b):sym(a), position(b){}
};
class Solution {
public:
int longestValidParentheses(string s) {
if(s.empty())return 0;
stack<Symbol> st;
int len = s.length();
int *f = new int[len];
int ret = 0;
int num = 0;
f[0] = 0;
for(int i=0;i<s.length();i++){
Symbol temp(s[i],i);
if(s[i] == '('){
st.push(temp);
f[i] = 0;
}
else{
if(!st.empty()){
Symbol m = st.top();
if(m.position-1>0) f[i] = f[m.position-1] + i - m.position + 1;
else
f[i] = i - m.position + 1;
//cout<<m.position-1<<" "<<f[i]<<endl;
st.pop();
}
else
f[i] = 0;
}
ret = max(ret,f[i]);
}
return ret;
}
};