数据结构之栈之括号匹配问题

数据结构实验之栈四:括号匹配

Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
 给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。

Input
 输入数据有多组,处理到文件结束。
Output
 如果匹配就输出“yes”,不匹配输出“no”
Example Input
sin(20+10)
{[}]
Example Output
yes
no
代码:
思路:凡是遇到左括号就进栈,若遇到右括号与栈顶元素相比较
      1:若相匹配,则栈顶出栈,继续比较下一个元素,直至最后所有的元素都比较完,且栈为空,则证明群补匹配成功
      2:不匹配:(1)右括号与站顶元素不匹配
                 (2)比较元素为右括号。而栈为空
                 (3)元素比较完了,而栈不为空

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxsize 110
typedef struct BiTNode
{
  char data;
  struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
int Search(char mid[],char a,int is,int n)//规定了查询范围
{
    int i;
    for(i = is;i<=n;i++)
    {
        if(a==mid[i])
            return i;
    }
    return -1;
}
BiTree CrtBT(char pre[],char mid[],int ps,int is,int n)//已知先序和后序创建二叉树
{
    BiTree root;
    int k;
    if(n==0) root = NULL;  //如果字符串中没有元素,则该子树为空
    else
    {
      k = Search(mid,pre[ps],is,is+n-1);  //不为空的话,则pre[PS]为根,首先在中序中找到根的位置
      if(k==-1) root = NULL;//k= -1,说说明未查询到、则为空
      else
      {
          root = (BiTree)malloc(sizeof(BiTNode));//先开辟空间
          if(!root) return 0;
          root->data = pre[ps];//赋值
          if(k==is) root->lchild = NULL;//is为中序的起始元素,若查询出的位置在is,说明该根的左孩子为空;
          else
          root->lchild = CrtBT( pre, mid, ps+1, is, k-is );//左孩子不为空,那么再次递归调用这个函数
          if (k==is+n-1) root->rchild = NULL;//如果最后一个元素为空,则说明没有右孩子
          else
          root->rchild = CrtBT( pre, mid, ps+1+(k-is), k+1, n-k+is-1 );//注意范围
        }

    }
    return root;
}
int lastPrint(BiTree root)//后序输出函数
{
    int depth,ldepth,rdepth;
    if(!root) depth = 0;
    if(root)
    {
        ldepth = lastPrint(root->lchild);
        rdepth = lastPrint(root->rchild);
        if(ldepth >rdepth )
            depth = ldepth + 1;
        else
            depth = rdepth + 1;
    }
    return depth;
}


int main()
{
    int m;
    while(scanf("%d",&m) !=EOF)
    {
        BiTree root;
        char pre[maxsize];
   char mid[maxsize];
   scanf("%s",pre);
   scanf("%s",mid);
   root = CrtBT(pre, mid, 0,0 ,strlen(mid));
   printf("%d",lastPrint(root));
   printf("\n");
    }


    return 0;
}




  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值