Suppose three kinds of parentheses are allowed in an expression: parentheses, square brackets, and braces. Write an algorithm to determine whether the various left parentheses in the expression match the right parentheses.
For example, input 2 + (3 + 4) * 2 + {[3]} - 8, output matching is correct; input 2 + (3 + 4 * [2) + {[3]} - 8, output matching is wrong.
Tip:
(1) When the left bracket is encountered, the stack will issue a symbol to see if it is matched. If pairing, continue until you have read all the symbols and the stack is empty. If there is a mismatch in the middle, or____ Then we can draw the conclusion that there is no match.
(2) You can also design a function whose return value is Boolean, whose parameter is the expression to be matched, and whose parameter is a string.
Both solutions have bugs: when the number of parentheses entered is greater on the left than on the right, for example{ }}}}}}}}}, a "match the correct bug" will appear.
Solution 1: for the header file sqstack.h, see[ Sequential stack algorithm library ], using Chain stack You can copy
- <span style="font-family:SimSun;font-size:12px;">#include <stdio.h>
- #include "sqstack.h"
- int main()
- {
- char c;
- char st[50];
- int d=1, i;
- SqStack *s;
- InitStack(s);
- printf("Please enter an expression:");
- scanf("%s", st);
- for(i=0; st[i]!='\0'&&d; i++)
- {
- switch(st[i])
- {
- case'(':
- case'[':
- case'{':
- Push(s, st[i]);
- break;
- case')':
- Pop(s, c);
- if(c!='(') d=0;
- break;
- case']':
- Pop(s, c);
- if(c!='[') d=0;
- break;
- case'}':
- Pop(s,c);
- if(c!='{') d=0;
- break;
- }
- }
- if(StackEmpty(s)&&d==1)
- printf("Correct pairing!!\n");
- else
- printf("Pairing error!!\n");
- return 0;
- }</span>
- #include <stdio.h>
- #include "sqstack.h"
- bool isMatch(char *st)
- {
- int d=1, i;
- char c;
- SqStack *s;
- InitStack(s);
- for(i=0; st[i]!='\0'&&d; i++)
- {
- switch(st[i])
- {
- case'(':
- case'[':
- case'{':
- Push(s, st[i]);
- break;
- case')':
- Pop(s, c);
- if(c!='(') d=0;
- break;
- case']':
- Pop(s, c);
- if(c!='[') d=0;
- break;
- case'}':
- Pop(s,c);
- if(c!='{') d=0;
- break;
- }
- }
- if(StackEmpty(s)&&d==1)
- return true;
- else
- return false;
- }
- int main()
- {
- char st[50];
- printf("Please enter an expression:");
- scanf("%s", st);
- if(isMatch(st))
- printf("Correct pairing!!\n");
- else
- printf("Pairing error!!\n");
- return 0;
- }