Detailed parentheses matching problem (STL stack)

Source: Internet
Author: User

1. The four possibilities of matching brackets:
① pairs of left and right brackets are not in correct order
② closing parenthesis More than opening parenthesis
③ opening parenthesis More than closing parenthesis
④ right and left brackets match correctly

2. Algorithm idea:
1. Sequential scan arithmetic expression (represented as a string), when you encounter three types of opening parenthesis, let the parentheses into the stack;
2. When scanning to a certain type of closing parenthesis, compare the current stack top element to match, if matching, the stack continues to judge;
3. If the top element of the current stack does not match the current scan, then the left and right brackets are paired in an incorrect order, and the matching fails and exits directly;
4. If the string is currently a type of closing parenthesis and the stack is empty, the closing parenthesis is more than the left parenthesis, and the match fails and exits directly;
5. At the end of the string loop scan, if the stack is non-empty (that is, the stack has some type of opening parenthesis), then the opening parenthesis is more than the closing parenthesis and the match fails;

6. The parentheses match correctly at the end of the normal.

#include <iostream>
#include <stack>
using namespace Std;
BOOL Match (char *p)
{

stack<char>s;
while (*P)
{
if ((*p== ' {') | | (*p== ' [') | | (*p== ' ('))
{
S.push (*P);
p++;
}
Else
{
if (S.empty ())//If there are no words, a closing parenthesis more than an opening parenthesis will cause an error because p will point to the illegal region, and *p will incorrectly
return false;
if (s.top () = = ' {' &&*p== '} ' | | S.top () = = ' [' &&*p== '] ' | | S.top () = = ' (' &&*p== ') ')
{
S.pop ();
p++;
}
Else
return false;
//p++;
}
}
if (!s.empty ())
return false;
Else
return true;
}
int main ()
{
Char s[10];
cin>>s;
if (Match (s))
cout<< "Kuohao is match!" <<endl;
Else
cout<< "Not match!" <<endl;
return 0;
}

Detailed parentheses matching problem (STL stack)

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.