栈篇实现符号字符串匹配问题。
可以输入不一样的括号字符串,测试是否匹配
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include "MyStack.h"
//#include "Coordinate.h"
using namespace std;
#define BINARY 2
#define OCTONARY 8
#define HEXADECIMAL 16
int main(int argc, char** argv)
{
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]);
switch(str[i])
{
case '[':
if (currentNeed != 0)
{
pNeedStack->push(currentNeed);
}
currentNeed = ']';
break;
case '(':
if (currentNeed != 0)
{
pNeedStack->push(currentNeed);
}
currentNeed = ')';
break;
default:
cout << "字符串符号不匹配" << endl;
return 0;
}
}
else
{
char elem;
pStack->pop(elem);
if(!pNeedStack->pop(currentNeed))
{
currentNeed = 0;
}
}
}
if(pStack->stackEmpty())
{
cout << "字符串符号匹配" << endl;
}
else
{
cout << "字符串符号不匹配" << endl;
}
delete pStack;
pStack = NULL;
return 0;
}
MyStack.h
#ifndef MYSTACK_H
#define MYSTACK_H
template <typename T>
class MyStack
{
public:
MyStack(int size); //初始化栈空间
~MyStack(); //回收栈空间
bool stackEmpty(); //判空
bool stackFull(); //判满
void clearStack(); //清空栈
int stackLength(); //已有元素
bool push(T elem); //入栈
bool pop(T &elem); //出栈
// char pop();
void stackTraverse(bool isFromButtom); //遍历
private:
T *m_pBuffer; //栈空间指针
int m_iSize; //栈容量
int m_iTop; //栈顶,元素个数
};
#include <iostream>
using namespace std;
template <typename T>
MyStack<T>::MyStack(int size) //初始化栈空间
{
m_iSize = size;
m_pBuffer = new T[size];
m_iTop = 0;
}
template <typename T>
MyStack<T>::~MyStack()
{
delete []m_pBuffer;
m_pBuffer = NULL;
}
template <typename T>
bool MyStack<T>::stackEmpty()
{
if (m_iTop == 0)
return true;
else
return false;
}
template <typename T>
bool MyStack<T>::stackFull()
{
if(m_iTop == m_iSize)
return true;
else
return false;
}
template <typename T>
void MyStack<T>::clearStack()
{
m_iTop = 0;
}
template <typename T>
int MyStack<T>::stackLength()
{
return m_iTop;
}
template <typename T>
bool MyStack<T>::push(T elem)
{
if(stackFull())
{
return false;
}
m_pBuffer[m_iTop] = elem;
m_iTop++;
return true;
}
template <typename T>
bool MyStack<T>::pop(T &elem)
{
if(stackEmpty())
{
return false;
}
m_iTop--;
elem = m_pBuffer[m_iTop];
return true;
}
//char MyStack::pop()
//{
// if(stackEmpty())
// {
// throw 1;
// }
// m_iTop--;
// return m_pBuffer[m_iTop];
//}
template <typename T>
void MyStack<T>::stackTraverse(bool isFromButtom)
{
if (isFromButtom)
{
for (int i = 0; i < m_iTop; i++)
{
cout << m_pBuffer[i];
// m_pBuffer[i].printCoordinate();
}
}
else
{
for (int i = m_iTop-1; i >= 0; i--)
{
cout << m_pBuffer[i];
// m_pBuffer[i].printCoordinate();
}
}
}
#endif