/*括号匹配
描述
给定一串字符,不超过100个字符,可能包括括号、数字、字母、标点符号、空格,编程
检查这一串字符中的( ) ,[ ],{ }是否匹配。
输入:在一行中给出一行字符串,不超过100个字符,可能包括括号、数字、字母、标点
符号、空格。
输出:如果括号配对,输出yes,否则输出no。
用例输入 1
sin(10+20)
{[}]
用例输出 1
yes
no
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
char data;
struct node *next;
}node,*linklist;
void linklist_daozhi(linklist head,int t,char a[]);//将链表倒置
int bianli(linklist head1,linklist head2);//遍历链表看倒置后是否相等
int main()
{
int i=0,t=0,n=0,m=0;
char s[110],a[110];
node *p,*q;
p=NULL; q=NULL;
linklist head1,head2;
head1=(node *)malloc(sizeof(node));
head1->next=NULL;
head2=(node *)malloc(sizeof(node));
head2->next=NULL;
p=head1;
while(scanf("%s",s)!=EOF)
{
int i=0,t=0,n=0,m=0;
n=strlen(s);
p=head1;
for(i=0;i<n;i++)
{
//只将输入的字符中的括号写入链表
if(s[i]=='('||s[i]==')'||s[i]=='['||s[i]==']'||s[i]=='{'||s[i]=='}')
{
a[t]=s[i];
t++;//记录括号个数
q=(node *)malloc(sizeof(node));
q->data=s[i];
p->next=q;
p=q;
}
else
continue;
}
q->next=NULL;
linklist_daozhi(head2,t,a);
m=bianli(head1,head2);
if(m==1)
printf("yes\n");
else
printf("no\n");
}
}
void linklist_daozhi(linklist head,int t,char a[])//将链表倒置
{
node *ptr1,*ptr2;
int i=0;
ptr1=head;
while(i<=t)
{
ptr2=(node *)malloc(sizeof(node));
ptr2->data=a[t];
ptr1->next=ptr2;
ptr1=ptr2;
t--;
i++;
}
ptr2->next=NULL;
}
int bianli(linklist head1,linklist head2)//遍历链表看倒置前后两个链表是否相等
{
int i=0,m=0;
head1=head1->next;
head2=head2->next;
while(head1!=NULL&&heads!=NULL)
{
i++;
if(head1->data==head2->data)
m++;
}
if(i==m)
return 1;
else
return 0;
}
参考GPT和自己的思路:首先,这段代码存在几个错误:
此外,如果只是检查括号是否匹配,使用链表这样的数据结构可能会显得过于复杂。可以直接使用栈,利用栈的先进后出的性质来检查括号是否匹配。具体做法为:读取到左括号时,将其入栈;读取到右括号时,弹出栈顶元素,判断是否与右括号匹配。如果不匹配,则说明括号不匹配。如果最终栈中还有元素,也说明括号不匹配。
对于判断括号是否匹配的链表方式出现超时的问题,可以尝试使用栈的方式来进行优化。具体步骤如下:
具体代码如下:
bool isMatch(string s) {
stack<char> stk;
for (char c : s) {
if (c == '(') {
stk.push(c);
}
else if (c == ')') {
if (stk.empty() || stk.top() != '(') {
return false;
}
stk.pop();
}
}
return stk.empty();
}
这样的栈方式时间复杂度为O(n),可以避免链表方式的超时问题。