主要是利用栈进行入栈出栈匹配,代码如下:
#include <iostream>
#include <string.h>
using namespace std;
#define STACK_SIZE 100
struct Stack
{
char strStack[STACK_SIZE];
int top;
};
void InitStack(Stack &s)
{
s.top = -1;
}
char Push(Stack &s, char c){
if (s.top + 1 > STACK_SIZE)
{
return 0;
}
s.top = s.top + 1;
s.strStack[s.top] = c;
return c;
}
bool IsEmpty(Stack &s)
{
if (s.top <= -1)
{
return true;
}
return false;
}
char Pop(Stack &s){
if (IsEmpty(s)){
return 0;
}
char c = s.strStack[s.top];
s.top = s.top - 1;
return c;
}
bool Match(char *str)
{
Stack stack;
InitStack(stack);
int strLength = strlen(str);
char c;
char popC;
for (int i = 0; i < strLength; ++i)
{
char c = str[i];
switch (c)
{
case '(':
case '[':
case '{':
Push(stack, c);
break;
case ')':
popC = Pop(stack);
if (popC != '(')
{
return false;
}
break;
case ']':
popC = Pop(stack);
if (popC != '[')
{
return false;
}
break;
case '}':
popC = Pop(stack);
if (popC != '}')
{
return false;
}
break;
default:
break;
}
}
if (IsEmpty(stack))
{
return true;
}
return false;
}
int main()
{
char str[STACK_SIZE];
cout << "请输入字串:" << endl;
cin >> str;
bool bMatch = Match(str);
if (bMatch)
{
cout << "匹配成功." << endl;
}
else {
cout << "匹配失败." << endl;
}
system("PAUSE");
return 0;
}
如果有优化的地方,欢迎指教。