The thought of the algorithm is as follows:
(1) Initially set up a empty stack, sequentially read in parentheses;
(2) If It is a right parentheses, or it matches the stack top element, or it is illegal;
(3) If It is a left parentheses, it'll be pushed into the stack.
When the algorithm are end, if the stack is empty and the parentheses matching is successful;
If the stack isn't empty, the parentheses matching is failing.
The codes is as follows (C + +):
1#include"stdafx.h"2#include <iostream>3#include"string.h"4 using namespacestd;5 #defineStackSize 1006 //define the structure of the stack7 structstack{8 CharStackstr[stacksize];9 inttop;Ten }; One //Initialize Stack A voidInitstack (Stack &s) { -S.top =-1; - } the //in-stack operation - voidPush (Stack &s,Charch) { - if(S.top = = stacksize-1) -cout <<"Station is full"<<Endl; + Else{ -s.top++; +S.stackstr[s.top] =ch; A } at } - //out of stack operation - CharPop (Stack &s) { - if(S.top = =-1) - return 0; - Else{ in CharCH =S.stackstr[s.top]; - returnch; to } + } - //determine if the stack is empty the intIsEmpty (Stack &s) { * if(S.top = =-1) $ return 0;Panax Notoginseng Else - return 1; the } + //Bracket Matching A intPrintmatchedpairs (Char*str) { the stack S; + Initstack (s); - intStrLen =strlen (str); $ for(inti =0; i < StrLen; i++){ $ CharCH =Str[i]; - Switch(CH) { - Case '(': the Case '[': - Case '{':Wuyi Push (S, ch); the Break; - Case ')': Wu if(Pop (s)! ='(') - return 0; About Break; $ Case ']': - if(Pop (s)! ='[') - return 0; - Break; A Case '}': + if(Pop (s)! ='{') the return 0; - Break; $ } the } the intRe =0; theRe =IsEmpty (s); the if(Re = =0) - return 0; in if(Re = =1) the return 1; the } About intMain () { the Charstr[ -]; thecout <<"Please enter a string of parentheses:"<<Endl; theCIN >>str; + intRe=printmatchedpairs (str); - if(Re = =0) thecout <<"parentheses match exactly"<<Endl;Bayi Else thecout <<"parentheses do not match"<<Endl; the return 0; -}