# 栈及栈运用之括号匹配

template<typename T>
class Stack
{
public:
Stack()
:_array(NULL)
,_size(0)
, _capacity(0)
{}
~Stack()
{
if (_array)
{
delete[] _array;
}
}
void Push(const T& data)
{
CheckCapacity();
_array[_size++] = data;
}
void Pop()
{
if (!Empty())
{
_size--;
}
}
T& Top()
{
assert(_size != 0);
return _array[_size-1];
}
T& Top()const
{
assert(_size != 0)
return _array[_size-1];
}
size_t Size()const
{
return _size;
}
bool Empty()const
{
return !_size;
}
private:
void CheckCapacity()
{
if (_size == _capacity)
{
_capacity = _capacity * 2 + 3;
T *ptemp = new T[_capacity];
if (_size)
{
for (size_t i = 0; i < _size; i++)
{
ptemp[i] = _array[i];
}
delete[] _array;
}
_array = ptemp;
}
}

T* _array;
size_t _capacity;
size_t _size;
};

（1）、左括号多了。
（2）、右括号多了。
（3）、括号顺序错了。
（4）、括号匹配正确。

bool MatchBrackets(char* pStr)
{
assert(pStr != NULL);
Stack<char> stack_char;
size_t len = strlen(pStr);
for (size_t i = 0; i < len; i++)
{
if (pStr[i] != '(' && pStr[i] != ')'&&
pStr[i] != '[' && pStr[i] != ']'&&
pStr[i] != '{' && pStr[i] != '}')
continue;
if (pStr[i] == '(' || pStr[i] == '[' || pStr[i] == '{')
{
stack_char.Push(pStr[i]);
}
else
{
if (stack_char.Empty())
{
cout << "右括号多了" << endl;
return false;
}
char ch = stack_char.Top();
if (ch == '(' && pStr[i] == ')' ||
ch == '['&&pStr[i] == ']' ||
ch == '{'&&pStr[i] == '}')
{
stack_char.Pop();
}
else
return false;
}
}
if (!stack_char.Empty())
{
cout << "左括号多了" << endl;
return false;
}
return true;
}

void test1()
{
char str[] = “abc{cd(dfsfs[fksd]}”;
if (MatchBrackets(str))
cout << “匹配正确”;
}

void test2()
{
char str[] = "abc{cd(dfs)fs[fksd]}}";
if (MatchBrackets(str))
cout << "匹配正确";
}

void test2()
{
char str[] = "abc{cd(dfs)f)s[fksd]}";
if (MatchBrackets(str))
cout << "匹配正确";
else
cout << "匹配错误";
}

void test2()
{
char str[] = "abc{cd(dfs)fs[fksd]}";
if (MatchBrackets(str))
cout << "匹配正确";
else
cout << "匹配错误";
}