1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 class Matcher{ 6 public: 7 Matcher(string str); 8 ~Matcher(){ }; 9 int match(); 10 private: 11 string str; 12 }; 13 14 Matcher :: Matcher(string str){ 15 this->str = str; 16 } 17 18 int Matcher :: match() 19 { 20 string S; /*定义一个字符对象 */ 21 int i, top = -1; /* top为字符对象S的尾指针 */ 22 for (i = 0;str[i] != ‘\0‘ ; i++) /* 依次对str对象的每个字符, str[i]进行处理 */ 23 { 24 if (str[i] == ‘)‘) { /*当前扫描的字符是右括号*/ 25 if (top > -1) top--; /*出栈前判断栈是否为空*/ 26 else return -1; 27 } 28 else if (str[i] == ‘(‘) /*当前扫描的字符是左括号*/ 29 S[++top] = str[i]; /*执行入栈操作*/ 30 } 31 if (top == -1) return 0; /*栈空则括号正确匹配*/ 32 else return 1; 33 } 34 35 36 int main( ) 37 { 38 string str; /*定义尽可能大的字符数组以接收键盘的输入*/ 39 int k; /*k接收调用函数Match的结果*/ 40 cout << "请输入一个算术表达式:"; 41 cin >> str; /*将表达式以字符串方式输入*/ 42 Matcher m(str); 43 k = m.match( ); /*函数调用,实参为字符数组的首地址*/ 44 if (k == 0) 45 cout << "正确匹配\n"; 46 else if (k == 1) 47 cout << "多左括号\n"; 48 else 49 cout << "多右括号\n"; 50 return 0; 51 }
原文:https://www.cnblogs.com/dss-99/p/14100559.html