问题描述:从左至右读取表达式,读到运算对象和运算符,不做任何动作,直接往下继续读,读到括号,要对括号的使用是否正确进行检查。
如: {[ ]( [ ][ ])} 为合法
#include<cstdio>
#include<iostream>
#include<cstring>
#define MAXSIZE 20
typedef struct SeqStack
{
char data[MAXSIZE];
int top;
}SeqStack;
int Bracket_Check(char *a)
{
int i;
SeqStack s;
s.top = -1;
for (i = 0; a[i] != '\0'; i++)
{
if (a[i] == '(' || a[i] == '[' || a[i] == '{')
s.data[++s.top] = a[i];
if (a[i] == ')' || a[i] == ']' || a[i] == '}')
{
if ((a[i] == ')' && s.data[s.top] == '(') || (a[i] == ']' && s.data[s.top] == '[') || (a[i] == '}' && s.data[s.top] == '{'))
s.top--;
else
return 0;
}
}
if (s.top == -1)
return 1;
else
return 0;
}
int main()
{
char input[MAXSIZE];
int check;
gets_s(input, MAXSIZE);
check = Bracket_Check(input);
if (check)
printf("Yes\n");
else
printf("No\n");
system("pause");
}
编译环境: Visual Studio
本文介绍了一个简单的C++程序,用于检查字符串中括号(包括圆括号、方括号和花括号)是否正确配对。通过使用顺序栈的数据结构实现括号匹配的算法,并给出了完整的代码示例。
429

被折叠的 条评论
为什么被折叠?



