您的位置:首页 > 其它

九度 1342 寻找最长合法括号序列II

2011-12-09 11:11 183 查看
http://ac.jobdu.com/problem.php?id=1342

开始时没太读懂题, “去掉一些括号" 其实换句话说,就是看看有多少括号匹配过。。。 比上一个容易些,不用管连续不连续,用上一题的代码就可以

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stack>
using namespace std;
int N;
char str[1000002];
bool flags[1000002] = { false };

stack < int >S;
bool match(char a,char b)
{
if(a=='('&&b==')')
return true;
return false;
}
int main ()
{
while (scanf("%s",str)!= EOF)
{
//scanf ("%s", str);
while (!S.empty ())
S.pop ();
memset (flags, false, sizeof (flags));
S.push (0);
int i, j;
int len = strlen (str) - 1;
for (i = 1; i <= len; i++)
{
if (S.empty ())
S.push (i);
else if (match (str[S.top ()], str[i]))
{
flags[i] = true;
flags[S.top ()] = true;
S.pop ();
}
else
S.push (i);
}
int max_len=0;
for(i=0;i<=len;i++)
if(flags[i])
max_len++;
printf("%d\n",max_len);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: