Arithmetic

C语言-括号匹配问题

PineappleCat · 4月16日 · 2019年 738次已读

Description
 输入一串字符串,编写算法判断字符串中的括号是否匹配,如果匹配,输出1,否则输出0。

注: 只考虑半角括号:( ) { } [ ],不考虑全角括号:( ) 【 】

例如:{ab123[(3*6-(4+3)) {223}[999]hhh}

字符串中的括号匹配。

{323[ab]()(123}

字符串中的括号不匹配。

提示:利用栈实现。

Input
 输入可以包含各种括号、数字、字母等符号的字符串。

Output
 括号匹配输出1,否则输出0。

Sample Input
sample 1:
{ab123[(3*6-(4+3)){223}[999]hhh}

sample 2:
{323[ab]()123}
Sample Output
sample1:
0
sample2:
1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FALSE 0
#define TRUE 1
int  match(char a,char b)
 {
    if(a=='('&&b==')')
        return TRUE;
    if(a=='['&&b==']')
        return TRUE;
    if(a=='{'&&b=='}')
        return TRUE;
    return FALSE;
}
int Bice(char* s)
{
    int i,n=strlen(s),top=-1;
    char st[n];
    for(i=0;i<n;i++)
    {
        if(s[i]==')'||s[i]==']'||s[i]=='}')
        {
            if(top>=0&&match(st[top],s[i]))
                top--;
            else
                return FALSE;
        }
        else if(s[i]=='('||s[i]=='['||s[i]=='{')
            st[++top]=s[i];
    }
    if(top==-1)
        return TRUE;
    return FALSE;
}
int main(){
   char array[100];
    gets(array);
    int i;
    i=Bice(array);
    if(i==1){
        printf("1");
    }
    else{
         printf("0");
    }
    return 0;
}

Click here to view the copyright notice of this site(点击此处查看本站版权声明)
0 条回应

必须 注册 为本站用户, 登录 后才可以发表评论!