之前大风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;
}
}