括号匹配
链接:栈的实现
demo.cpp
#include "MyStack.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
/*
括号匹配
[()] [()()] [()[()]]
*/
int main()
{
//扫描字符串中的括号
MyStack<char>* pStack = new MyStack<char>(30);
//需要的括号
MyStack<char>* pNeedStack = new MyStack<char>(30);
char str[] = "[()[(]]"; //字符串内容
char currentNeed = 0; //当前需要的字符
for (int i = 0; i < strlen(str); i++)
{
//遍历整个字符串,判断当前字符是否是需要的字符
if (str[i] != currentNeed)
{
pStack->push(str[i]); //不是则入栈
//修改当前需要的字符串,如果当前currentNeed有值,则用栈保存起来
switch (str[i])
{
case '[':
if (currentNeed != 0)
{
pNeedStack->push(currentNeed);
}
currentNeed = ']';
break;
case '(':
if (currentNeed != 0)
{
pNeedStack->push(currentNeed);
}
currentNeed = ')';
break;
default: //如果多一个右括号,
cout << "字符串不匹配" << endl;
system("pause");
return 0;
}
}
else
{
char elem;
pStack->pop(elem);
if (!pNeedStack->pop(currentNeed))
{
//如果pop失败则,返回0
currentNeed = 0;
}
}
}
if (pStack->stackEmpty())
{
cout << "字符串匹配" << endl;
}
else
{
cout << "字符串不匹配" << endl;
}
delete pStack;
pStack = NULL;
delete pNeedStack;
pNeedStack = NULL;
system("pause");
return 0;
}