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>
int main()
{
char stack[150],s[150];
int top,low,i,n,l,find;
scanf("%d",&n);
getchar();
while(n--)
{
find = 1;
gets(s);
memset(stack,0,sizeof(stack));
top=low=-1;
l=strlen(s);
for(i=0;i<l;i++)
{
if(s[i]=='('||s[i]=='[')
{//如果是左括号则入栈,等待匹配
stack[++top]=s[i];
}
else if(s[i]==')')
{//如果为右小括号
if(stack[top]=='(')//可以匹配
top--;
else
{//不能匹配
find=0;
break;
}
}
else if(s[i]==']')
{//如果为右中括号
if(stack[top]=='[')//可以匹配
top--;
else
{//不能匹配
find=0;
break;
}
}
else
{//存在其他字符时
find=0;
break;
}
}
if(i==l&&top!=low)
find=0;//存在多余的括号
if(find==0)
{
printf("No\n");
}
else
{
printf("Yes\n");
}
}
return 0;
}
本文深入探讨了经典的括号匹配问题,通过一个具体的程序实例,详细讲解了如何使用栈来检查由圆括号和方括号组成的字符串是否正确配对。代码采用C语言实现,通过逐个扫描字符串中的字符,并利用栈进行出栈和入栈操作,判断括号的正确性。
&spm=1001.2101.3001.5002&articleId=86548033&d=1&t=3&u=9b0d0d0eb9b341f88901e1574d4d415a)
507

被折叠的 条评论
为什么被折叠?



