Bracket Matching algorithm

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.