32、Longest Valid Parentheses
最長有效括號
給定一個僅僅包含'('
或 ')'
的字符串,找出其中最長有效括號組成的子集的長度。字符串
"(()"
,它的最長有效號符子集是"()"
,長度爲2。另一個例子
")()())"
,它的最長有效括號子集是"()()"
,長度是4。分析:
代碼:
class Solution {
public:
class pair//一對
{
public:
int position;//位置
int FF;//翻轉器
};
int longestValidParentheses(string s) {
stack<pair> stack;
pair temp;
temp.position=-1;
temp.FF=false;
stack.push(temp);//棧頂添加一個空元素,防止溢出
int res=0;//字符串長度
for(int i=0;i<s.length();i++)
switch(s[i])
{
case'('://進棧
temp.position=i;
temp.FF=true;
stack.push(temp);
break;
case')':
if(stack.empty())//進棧
{
temp.position=i;
temp.FF=false;
stack.push(temp);
}
else if(stack.top().FF)//出棧
{
stack.pop();
res=max(res,i-stack.top().position);
}
else//進棧
{
temp.position=i;
temp.FF=false;
stack.push(temp);
}
break;
default:
break;
}
return res;
}
};