括号匹配算法
算法思想
/*
括号匹配算法
扫描字符串,遇到左括号 入栈,遇到右括号 出栈顶元素
*/
数据结构 定义存字符串的栈
#include <stdio.h>
#include <string.h>
#define Maxsize 10
typedef struct
{
char str[Maxsize];
int top;
}Stack;
void InitStack(Stack &S)
{
S.top = -1; // 栈空
}
bool isEmpty(Stack S)
{
return S.top == -1;
}
bool Push(Stack &S, char &x)
{
if(S.top >= Maxsize -1)
{
return false; // 栈满
}
S.str[++S.top] = x;
return true;
}
bool Pop(Stack &S, char &x)
{
if(S.top == -1)
{
return false;
}
x = S.str[S.top--];
return true;
}
核心算法
bool bracketCheck(char str[], int len)
{
Stack S;
InitStack(S);
for(int i=0; i<len; i++) // 扫描
{
if(str[i]=='(' || str[i]=='[' || str[i]=='{')
{
Push(S, str[i]); // 左括号入栈
}
else
{
if(S.top == -1)
{
return false;
}
char c;
Pop(S, c);
if(str[i]==')' && c!='(')
{
return false;
}
if(str[i]==']' && c!='[')
{
return false;
}
if(str[i]=='}' && c!='{')
{
return false;
}
}
}
return isEmpty(S);
}
int main()
{
char str[Maxsize];
puts("Please input a str:");
scanf("%s", &str);
printf("The %s is matching ?: %d", str, bracketCheck(str, strlen(str)));
return 0;
}
测试
________________________________________________________
Every good deed you do will someday come back to you.
Love you,love word !