preface
In the process of my own study , It is inevitable to encounter many complex algorithm problems . A good way to solve the problem is to find information , Refer to others' logical thinking . There are some problems that cannot be found , It may also be that the article is too messy , Too difficult , Too complicated . Here I share my personal views and ideas .
case analysis
In the process of coding , Brackets are often used , If we use inappropriate code , Then the compiler will report an error . Of course, at my level, it is impossible to move the compiler mechanism here .
for instance , We entered {[]}() This set of parentheses , Obviously , This is a correct set of parentheses .
Another example is , We entered {[}] This set of parentheses , obviously , This is a wrong set of parentheses .
So how to realize the function of judging whether it is legal through the program ?
One of the principles is called —— Stack .
Let's start with an example .
We put all the left parentheses on the stack by looping . Right parenthesis encountered , Match with the top of the stack .
A successful pair takes an element from the stack .
adopt top-- The operation of points to the next element of the stack .
The above example is to put all the left parentheses on the stack at one time .
What about this example ?
When we want to put elements on the stack , Suddenly hit the right parenthesis , We can also perform this operation in this way .
code implementation
#include <string.h> #include <stdio.h> int main() { char arr[100]; char
s[100]; gets(arr); int len=0; int top=-1; len=strlen(arr); for(int
i=0;i<len;i++) { if(arr[i]=='{'||arr[i]=='['||arr[i]=='(') { top++;
s[top]=arr[i]; }
if((arr[i]=='}'&&s[top]=='{')||(arr[i]==']'&&s[top]=='[')||(arr[i]==')'&&s[top]=='('))
{ top--; } } if(top==-1) printf("yes\n"); else printf("no\n"); return 0; }
Technology
Daily Recommendation