Title: Design An algorithm that determines whether the parentheses match in the expression entered by the user, which may contain parentheses, brackets, and curly braces.
Idea: Create a sequential stack that will be stacked when there is an opening parenthesis in the expression, and when the closing parenthesis appears, stack the top element of the stack to check if it matches the current closing parenthesis. Finally, if the stack is empty, the parentheses in the expression match.
Code:
#include <iostream>#include <string>using namespace STD;#define MaxSize//String Stacksclassstack{Char*data;intTop Public: Stack (); ~stack ();BOOLIsEmpty ();BOOLPush (Chare);BOOLPop (Char& e);}; Stack::stack () {data =New Char[MaxSize]; top =-1;} Stack::~stack () {Delete[] data;}BOOLStack::isempty () {return(Top = =-1);}BOOLStack::P Ush (CharE) {if(top = = maxsize-1)return false;//full-stacktop++; Data[top] = e;return true;}BOOLStack::P op (Char& E) {if(Top = =-1)return false;//Stack emptye = Data[top]; top--;return true;}BOOLIsMatch (CharStr[],intN) {intI=0;CharE Stack St;//Build sequential stacks while(i<n) {if(Str[i] = =' ('|| Str[i] = =' ['|| Str[i] = =' {') St. Push (Str[i]);Else{if(Str[i] = =' ) ') {if(!st. Pop (e))return false;if(e!=' (')return false; }if(Str[i] = ='] ') {if(!st. Pop (e))return false;if(e!=' [')return false; }if(Str[i] = ='} ') {if(!st. Pop (e))return false;if(e!=' {')return false; }} i++; }if(St. IsEmpty ())return true;Else return false;//Traversal string after the stack is not empty description has mismatched characters}voidMain () {cout<<"Please enter an expression:"<<endl;CharStr[] ="";Cin>>str;intn =strlen(str);if(IsMatch (Str,n))cout<<"Expression"<<str<<"The parentheses in the" are matched "<<endl;Else cout<<"Expression"<<str<<"The parentheses in the" are mismatched "<<endl;}
Test Data 1:9*{8+[7-(6+5)]}
Test result 1:
Test data 2:[[[[[)] []]
Test Result 2:
Common algorithmic questions: determine if the expression brackets match