【大风】matrix:valid parentheses括号匹配代码分享

本文介绍了一个使用栈数据结构实现的有效括号匹配算法。该算法通过遍历字符串中的括号,并利用栈来跟踪左括号,确保每一对括号正确闭合。文章详细解释了算法流程并提供了完整的 C 语言实现。

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

#include <stdio.h>
#include <string.h>
//数据结构:栈
//算法:抓取到左括号,就将它推入栈(push);抓取到右括号,就pop,取出一个左括号,判断是否匹配,如果匹配则继续;不匹配立即结束循环,输出false。
int stack[1000];
int len_stack;

int pop(void)
{
//自己想   
}

void push(int new_element)
{
   //自己想
 }

int trans(char c)//把括号转化为数字来处理
{
    switch (c)
    {
        case '{':return 1;
        case '}':return 2;
        case '[':return 3;
        case ']':return 4;
        case '(':return 5;
        case ')':return 6;
    }

}

int main()
{
    char exp[10000];
    scanf("%s",&exp);
    long len_exp =strlen(exp);

    int boo=1;//boo为1代表匹配,为0代表不匹配

    int t,i;

    len_stack=0;

    for (i=0;i<len_exp;i++)
    {
        t=trans(exp[i]);
        if (t%2==0) 
        {
            if (len_stack==0) //如果栈中没了元素,说明右括号前面没有左括号,  
            {
                boo=0;
                break;
            }

            else
            {
                if (pop()+1!=t) 
                {
                    boo=0;
                    break;
                }

            }
        }
        else  push(t);

    }
    if (len_stack!=0) boo=0;

    if (boo==0) printf("False\n");
        else    printf("True\n");
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值