数据结构--栈的应用-括号匹配算法C++(模板类实现)
作者:
AmbitionX
,
2022-05-04 14:44:50
,
所有人可见
,
阅读 225
#include <iostream>
#include <cstring>
using namespace std;
const int Size = 100;
class Matcher
{
public:
Matcher(string str);
int Match();
private:
string str;
};
Matcher :: Matcher(string str)
{
this->str = str;
}
int Matcher :: Match()
{
char S[Size];
int i, top = -1;
for (i = 0; str[i] != '\0'; i++)
{
if (str[i] == ')')
{
if (top > -1) top --;
else return -1;
}
else if (str[i] == '(') S[++ top] = str[i];
}
if (top == -1) return 0;
else return 1;
}
int main()
{
string str;
cout << "输入算术表达式" << endl;
cin >> str;
Matcher M{str};
int k = M.Match();
if (k == 0) cout << "正确匹配\n";
else if (k == 1) cout << "多左括号\n";
else cout << "多右括号\n";
return 0;
}