Common algorithm questions: judge whether expression brackets match, and expression brackets
Question: design an algorithm to determine whether the brackets in the expression you entered match. The expressions may contain parentheses, braces, and braces.
Idea: Create an ordered stack. When the expression contains left parentheses, import it into the stack. When right parentheses appear, the top elements of the stack are output from the stack and check whether they match the current right parenthesis. If the stack is empty, the parentheses in the expression match.
Code:
# Include <iostream> # include <string> using namespace std; # define MaxSize 20 // string Stack class Stack {char * data; int top; public: Stack ();~ Stack (); bool IsEmpty (); bool Push (char e); bool Pop (char & e) ;}; Stack: Stack () {data = new char [MaxSize]; top =-1;} Stack ::~ Stack () {delete [] data;} bool Stack: IsEmpty () {return (top =-1);} bool Stack: Push (char e) {if (top = MaxSize-1) return false; // Stack full top ++; data [top] = e; return true;} bool Stack: Pop (char & e) {if (top =-1) return false; // empty stack e = data [top]; top --; return true;} bool IsMatch (char str [], int n) {int I = 0; char e; Stack st; // create an ordered Stack while (I <n) {if (str [I] = '(' | str [I] = '[' | str [I] = '{') st. pus H (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; // If the stack is not empty after traversing the string, it indicates that there are unmatched characters} void main () {cout <"Enter the expression: "<endl; char str [] =" "; cin> str; int n = strlen (str); if (IsMatch (str, n )) cout <"expression" <str <"brackets match" <endl; else cout <"expression" <str <"Parentheses do not match" <endl ;}
Test data: * {8 + [7-(6 + 5)]}
Test result 1:
Test data 2: [[[[)]
Test result 2: