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)