【艾米莉娅】matrix:valid parentheses括号匹配代码分享(非堆栈版)

本文介绍了一种不使用堆栈实现括号匹配的有效算法。通过对输入字符串中括号的逐一判断,确保括号正确闭合。适用于基础数据结构教学。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前大风dalao使用堆栈实现了括号匹配,但毕竟堆栈是过于超前的内容,很多小伙伴看不懂。因而分享一下自己做的非堆栈型括号匹配代码。

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.

//
// Source Code.cpp 
//
// Common Test Emilia 
//
// Created by Emilia on 2016/11/20
// Copyright © 2016 Emilia. All rights reserved.
//

#include<stdio.h>
#include<string.h>

int sym[100], pos = 0, length, times, cor = 0;
char input[100];

int main(void)
{
    scanf("%s", &input);
    length = strlen(input); //在输入之后,利用strlen命令获取当前数组有效位长度。
                            //主要是为了给之后的判断模块提供循环次数。

//由于DDL的推后,特意修改了部分代码,因而该公开版本并不完美,存在严重的圈复杂度超标问题,仅供思路上的交流。
//尽管在圈复杂度上有一定缺陷,但通过一定的修饰之后本代码可以达到满分。
//诶?你问我怎么修饰……等DDL过了再说吧~

    for (times = 0;times < length;times++) //判断模块
    {
        if (input[times] == '(')
            sym[++pos] = 1;
        else
            if (input[times] == '[')
                sym[++pos] = 2;
            else
                if (input[times] == '{')
                    sym[++pos] = 3;
                else
                    if (input[times] == ')' && sym[pos--] == 1)
                        cor = 1;
                    else
                        if (input[times] == ']' && sym[pos--] == 2)
                            cor = 1;
                        else
                            if (input[times] == '}' && sym[pos--] == 3)
                                cor = 1;
                            else
                            {
                                printf("False\n");
                                cor = 3;
                                times = length;
                            }
    }

    if (cor == 1)
    {
        printf("True\n");
    }
    else if (cor != 3)
    {
        printf("False\n");
    }

    getchar();
    getchar(); //两个getchar()命令主要是方便VS下查看运行结果。

    return 0;
}


}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值