http://vjudge.net/contest/view.action?cid=50788#problem/A
You are given a string consisting of parentheses () and []. A string of this type is said to be correct:
-
(a)
- if it is the empty string (b)
- if A and B are correct, AB is correct, (c)
- if A is correct, (A ) and [A ] is correct.
Write a program that takes a sequence of strings of this type and check their correctness. Your program can assume that the maximum string length is 128.
Input
The file contains a positive integer n and a sequence of n strings of parentheses () and [] , one string a line.
Output
A sequence of Yes or No on the output file.
Sample Input
3 ([]) (([()]))) ([()[]()])()
Sample Output
Yes No Yes
题目大意:给出你一串由[ ] ( )四种字符组成的字符串,判断是否合法的字符串。
大体思路:
方法一:
因为以前做过一道括号的最大匹配的题,我想着如果最大匹配正好和字符串的长度是一致的时候我们可以确定该字符串是合法的字符串,不知道什么会超时==
/*
==超时的代码==
*/
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
char a[130];
int dp[130][130];
int main()
{
int T;
scanf("%d%*c",&T);
while(T--)
{
scanf("%s",a+1);
memset(dp,0,sizeof(dp));
int n=strlen(a+1);
if(n%2)
{
printf("No\n");
continue;
}
/* for(int i=1;i<=n;i++)
cout <<a[i];
cout <<"**"<<endl;*/
for(int i=n-1; i>=0; i--)
for(int j=i+1; j<=n; j++)
{
dp[i][j]=dp[i+1][j];
for(int k=i+1; k<=j; k++)
if((a[i]=='('&&a[k]==')')||(a[i]=='['&&a[k]==']'))
dp[i][j]=max(dp[i][j],dp[i+1][k-1]+dp[k+1][j]+2);
}
/*for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
printf("%d ",dp[i][j]);
printf("\n");
}*/
if(dp[1][n]==n)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}
方法二:
利用栈的特殊进出顺序。详见代码
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
stack<char> s;
char str[130];
int main(void)
{
int t;
scanf("%d", &t);
getchar();
while (t--)
{
gets(str);
int len = strlen(str);
if (len & 1)
puts("No");
else
{
if (!s.empty())
s.pop();
s.push('0');
for (int i = 0; i < len; ++i)
{
if (str[i] == '(' || str[i] == '[')
s.push(str[i]);
else if (str[i] == ')')
{
if (s.top() == '(')
s.pop();
else
{
s.push('1');
break;
}
}
else
{
if (s.top() == '[')
s.pop();
else
{
s.push('1');
break;
}
}
}
puts(s.top() == '0' ? "Yes" : "No");
}
}
return 0;
}