Parentheses matching, is a string processing of a problem, more common, here summarizes the general idea, with my personal code.
General idea: Data structure selection stack, read to the left parenthesis in the stack, read to the right parenthesis to determine whether the match, matching the left bracket out of the stack, the non-bracket character continues to read down
The code is as follows:
1#include <iostream>2#include <cstring>3#include <string>4#include <stack>5 6 using namespacestd;7 BOOLIs_match (stringstr) {8stack<Char>s;9 for(intI=0; I<str.length (); i++){Ten Switch(Str[i]) One { A Case '{': - Case '[': - Case '<': S.push (Str[i]); Break; the Case '}': - Case ']': - Case '>':Chartemp=Str[i]; - if((!s.empty ()) && (temp=='}'&&s.top () = ='{')|| (temp==']'&&s.top () = ='[')|| (temp=='>'&&s.top () = ='<')){ + S.pop (); - } + Else{ Acout<<"parentheses do not match"<<Endl; at return false; - } - } - } - if(!S.empty ()) { - return false; in } - Else{ to return true; + } - } the * intMain () $ {Panax Notoginseng BOOLAns=is_match ("<,34342}>"); -cout<<ans<<Endl; the}
Bracket Matching algorithm