You are given a string consisting of parentheses()and[]. A string of this type is said to becorrect:(a)if it is the empty string (b) if A and Bare correct,ABis correct,(c)ifAis 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 integernand a sequence ofnstrings of parentheses ‘()’ and ‘[]’, one stringa line.
Output
A sequence of ‘Yes’ or ‘No’ on the output file.
Sample Input
3
([])
(([()])))
([()[]()])()
Sample Output
Yes
No
Input
The file contains a positive integernand a sequence ofnstrings of parentheses ‘()’ and ‘[]’, one stringa 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>
int main()
{
int i,j,k,t;
char a[1200];
scanf("%d",&t);
getchar();
while(t--)
{
memset(a,0,sizeof(a));
gets(a);
int l=strlen(a);
if(l==0)
printf("Yes\n");
else
{
int x=0;
int y=0;
int find=0;
for(i=0;a[i]!='\0';i++)
{
if(a[i]=='(')
x++;
if(a[i]==')')
{
if(x==0)
{
find=1;
break;
}
else
{
if(y!=0)
{
if(a[i-1]!='[')
{
x--;
}
else
{
find=1;
break;
}
}
else
{
x--;
}
}
}
if(a[i]=='[')
y++;
if(a[i]==']')
{
if(y==0)
{
find=1;
break;
}
else
{
if(x!=0)
{
if(a[i-1]!='(')
{
y--;
}
else
{
find=1;
break;
}
}
else
{
y--;
}
}
}
}
if(find==1)
{
printf("No\n");
}
else
{
if(x==0&&y==0)
printf("Yes\n");
else
printf("No\n");
}
}
}
return 0;
}
代码(栈):
#include<stdio.h>
#include<string.h>
#include<stack> //栈的函数头文件
using namespace std;
int main()
{
int i,j,k,t;
char a[1200];
scanf("%d",&t);
getchar();
while(t--)
{
memset(a,0,sizeof(a));
gets(a);
int l=strlen(a);
if(l==0)
printf("Yes\n");
else
{
if(l%2==1)
printf("No\n");
else
{
stack<char>s;//声明栈的数据类型 int double char 也可以是一个结构体
int find=0;
for(i=0;i<l;i++)
{
if(a[i]=='('||a[i]=='[')
{
s.push(a[i]);//入栈
}
else
{
if(s.empty()==1)//判断栈的是否为空,空返回1,反之返回0
{
find=1;
break;
}
if(a[i]==')'&&s.top()=='(')//s.top()读取栈顶元素
{
s.pop();//删除栈元素
}
if(a[i]==']'&&s.top()=='[')
{
s.pop();
}
}
}
if(s.empty()==1&&find==0)
printf("Yes\n");
else
printf("No\n");
}
}
}
return 0;
}