When writing code, there are often two types of parentheses: parentheses "()" and curly braces "{}". Regardless of which parentheses are used, one of the important factors in program compilation is that the parentheses used can match.
When writing a program, parentheses can be nested, that is, "({)}"), but "({)" or "({}" does not meet the requirements.)
Brackets Match Project requirements: give any matching parentheses to determine if they match. When designing a program to determine the bracket matching problem, it is easy to use the stack structure:
- If you encounter the left parenthesis or the left brace, press the stack directly;
- If a closing parenthesis or closing brace is encountered, it is paired directly with the top element of the stack: if matched, the top element of the stack is stacked, whereas the parentheses do not match;
Implementation code
#include <stdio.h>#include<string.h>
inttop =-1;//Top variable indicates the position of the top element of the stackvoidPushChar*a,intelem)
{a[++top] =Elem;}
voidPopChar*a)
{ if(Top = =-1) return ; Top--;}
CharVisitChar*a)
{ //stack top element, not equal to the stack, if the stack is empty, to make the program does not error, return null character if(Top! =-1)
{ returnA[top]; }
Else
{return ' '; }}
intMain ()
{ Chara[ -]; Charbracket[ -]; printf ("Please enter a sequence of parentheses:"); scanf ("%s", bracket); GetChar (); intLength = (int) strlen (bracket); for(intI=0; i<length; i++)
{ //if it is an opening parenthesis, press the stack directly if(Bracket[i] = ='('|| Bracket[i] = ='{')
{Push (A, bracket[i]); }Else{ //if it is the right parenthesis, determine whether the top element of the stack matches, if matching, stack top elements of the stack, the program continues to run; otherwise, find the parentheses do not match, the output will exit if(Bracket[i] = =')')
{ if(Visit (a) = ='(')
{pop (a); }
Else
{printf ("parentheses do not match"); return 0; } }
Else
{if(Visit (a) = ='{')
{pop (a); }
Else
{printf ("parentheses do not match"); return 0; } } } } //If all parentheses match complete, the stack is empty, indicating that all parentheses match successfully if(Top! =-1)
{printf ("parentheses do not match"); }
Else
{printf ("Bracket Matching"); }}
Run Result: Enter the bracket sequence: {} () {parenthesis mismatch
Data structure 13: Bracket matching algorithm and C language implementation