思路:
自己没想出来,参考了一下网上大神的提示。
使用一个int栈,将左括号记为-1,右括号记为-2;遍历字符串。
1. 若为‘(’,则直接压入栈;
2. 若为‘)’,分情况讨论:
①. 若栈顶为‘-2’或栈空,则直接将-2压入栈;
②. 若栈容量为1,且栈顶为-1,将-1推出栈,推入2,代表此时有一对匹配括号;
③. 若栈容量为1,且栈顶大于0,说明此右括号不能配对且阻断了前后括号,直接推入-2;
④. 若栈size大于2:
若栈顶大于0,推出栈顶暂存为temp:观察此时栈顶,若为-1,则括号匹配,temp+2,推出栈顶,再观察此时栈顶,若大于0,推出与temp相加,再推入temp;
若栈顶为-1,括号匹配,推出栈顶,再观察此栈顶,若大于0,则推出累加2,再推回;否则,推入2。
int longestValidParentheses(string s) {
stack<int> st;
int len=s.length();
int maxlen=0,templen=0;
for(int i=0;i<len;i++)
{
if(s[i]==')'&&(st.empty()||st.top()==-2))
{
st.push(-2);
}
else if(s[i]==')'&&st.size()==1&&st.top()!=-2)
{
if(st.top()==-1)
{
st.pop();
st.push(2);
maxlen=max(maxlen,2);
}
else if(st.top()>0)
{
st.push(-2);
}
}
else if(s[i]==')'&&st.size()>=2&&st.top()!=-2)
{
if(st.top()>0)
{
int temp=st.top();
st.pop();
if(st.top()==-1)
{
st.pop();
temp+=2;
if(st.size()>0&&st.top()>0)
{
temp+=st.top();
st.pop();
}
st.push(temp);
maxlen=max(maxlen,temp);
}
else if(st.top()==-2)
{
st.push(-2);
}
}
else if(st.top()==-1)
{
st.pop();
if(st.top()>0)
{
int temp=st.top();
st.pop();
temp+=2;
st.push(temp);
maxlen=max(maxlen,temp);
}
else if(st.top()<0)
{
st.push(2);
maxlen=max(maxlen,2);
}
}
}
else if(s[i]=='(')
{
st.push(-1);
}
}
return maxlen;
}