当前位置:网站首页>USES the stack to determine whether a parenthesis matching
USES the stack to determine whether a parenthesis matching
2022-08-06 09:38:00 【Why are so many names taken?】
What is a stack?
Stack has several meanings, such as a linear table that follows the first-in-last-out rule (as opposed to "queue"); where the system allocates variable address space when the program is running, it follows the first-in-last-out principle (as opposed to "heap");In a storage medium of CPU registers, follow the principle of first-in, last-out when accessing
The stack we are talking about today is the first meaning
What is FIFO
First in, last out, that is, first in and last out.It's that simple.
For example I have data x, y, z.I put x on the stack first, then y on the stack, then z on the stack.When I want to take it out, first take out z, then take out y, then take out x

This is a simple diagram
Push to stack
Into the stack refers to data storage
pop
Popping refers to data fetching
The stack that C++ gives us
// import header file#include // stack is in std namespaceusing namespace std;// Define a stack, each element in the stack is of type intstack st;// push 1 to stackst.push(1);// push 2 onto the stackst.push(2);// return to top of stackint tmp = st.top();// pop, no return valuest.pop();// if stack is emptyif(st.empty()); What are parentheses :-)
Brackets are divided into parentheses "()", square brackets "[]", and curly brackets "{}", each of which is divided into left brackets "([{" and right brackets "}])".Each left parenthesis must be followed by the same right parenthesis, and the parentheses cannot be misplaced.i.e. ([{}]) but not ([{]})
What is a match for parentheses
To judge whether parentheses match is to judge whether the use of parentheses is reasonable.For details, see "What are parentheses" :-)
How to use the stack to judge whether brackets match?
Thoughts
The idea of using stack judgment is as follows:
1. Traverse the string
2. If parentheses are found
1) Determine whether it is a left bracket
If it is a left parenthesis, push it to the stack
Otherwise (it is the right parenthesis), pop the stack, and compare the result with the parentheses traversed. If it is not a parenthesis of the same type, return -1 directly (indicating an error)
3. After the traversal is completed, no errors are found, and the correct 0 is returned (indicates correct)
Code implementation
For (yin), (wei), then (wo), then (bi), (jiao), see (lan), this code is written in a source file.In actual development, the type definition, function declaration, header file inclusion, etc. should be placed in a .h file, the function function should be placed in a .c file, and the main function should be placed in the main.c file.Don't follow me, just put it in one file
#include #include #include // define an enumeration of bracket typestypedef enum{LITTLE, // parenthesesMIDDLE, // square bracketsLARGE, // curly bracketsERROR // error}brackets_t;// get parenthesis typebrackets_t get_brackets_type(char c){brackets_t result;switch(c){case '(':case ')':result = LITTLE;break;case '[':case ']':result = MIDDLE;break;case '{':case '}':result = LARGE;break;default:result = ERROR;break;}return result;}// Determine if the parenthesis is a left parenthesis, return 1int is_left(char c){if(c == '(' || c == '[' || c == '{')return 1;return 0;}// pop the stack if the stack is empty, return -1, otherwise return the top element of the stack// This sentence defines a generic (type placeholder), which will be changed to a specific type during compilation// This placeholder is TtemplateT pop(std::stack *st){// Check if the stack is emptyif(!(*st).empty()){ // Normal call if not emptyT result = (*st).top();(*st).pop();return result;}// If empty, return -1 of type T// use a more powerful coercionT *tmp; // create a temporary (T *) variableint itmp = -1; // create a temporary int variabletmp = (T *)&itmp; // For tmp to store the address of itmp, a forced conversion is requiredreturn *tmp; // use T's access rule to read the address of itmp}// Judging whether the bracket combination is correct, return 0 correctlyint is_brackets_right(const char *str){std::stack st; // build stack// iterate over the stringint len = strlen(str);for(int i = 0; i < len; i++){// store the type of the current parenthesisbrackets_t br = get_brackets_type(str[i]);// If it is a parenthesis, make a parenthesis judgmentif(br != ERROR){// if the current parenthesis is an opening parenthesisif(is_left(str[i]))// Then get the bracket type and store it on the stackst.push(br);// else pop the stack and compare the type with the current parenthesiselse {// pop the stackbrackets_t sr = pop(&st);// if the types are not equal return -1if(sr != br)return -1;}}}// end of the loop, if there is no problem, return 0return 0;}int main(void){char str[16];scanf("%s", str);int if_it = is_brackets_right(str);if(if_it == 0)printf("It is right\n");else printf("It is not right\n");return 0;} This is the primary usage of the stack - judging whether the parentheses match
边栏推荐
- 域名授权验证系统v1.0.6开源版本网站源码
- Usage of torch.utils.data in pytorch ---- Loading Data
- Hdu2022 Multi-School Training (5) BBQ
- 46道史上最全Redis面试题,面试官能问的都被我找到了(含答案)
- B. Luke is a Foodie(贪心/模拟)
- pytorch中 torch.utils.data的用法 ----加载数据篇
- 白色简洁大方公司企业网站源码 WordPress主题2款
- Smart three-piece - nanny-level teaching.
- ACM常用头文件
- Vant3——复选框点击其他后格外出现一个输入框
猜你喜欢
随机推荐
46 most complete Redis interview questions in history, I found all the interviewers asked (with answers)
Smart three-piece - nanny-level teaching.
nuxt页面访问速度优化
【Log】镜像源配置以及最新可用镜像源
定时任务 出现 A component required a bean named ‘xxx‘ that could not be found
Redis In Action —— Advanced —— Redis 的两种持久化方式 —— RDB 与 AOF 工作流程与原理 —— RDB 与 AOF 的对比 —— 囊括面试题
Usage of torch.utils.data in pytorch ---- Loading Data
【机器学习】贝叶斯分类器
pytorch中 torch.utils.data的用法 ----加载数据篇
干货,分布式数据库在金融核心场景的落地实践|腾讯云数据库
【内网横移方法与实验】
Web version Xshell supports FTP connection and SFTP connection [Detailed tutorial] Continue from the previous article
数组里的值放到另一个数组中,并转大写
《微信小程序-进阶篇》Lin-ui组件库源码分析-动画组件Transition(一)
一句话打印出文件夹及文件的树状结构图
网易云信音视频能力中台,聚焦银行业数字化转型
Dijkstr heap optimization
Neo4j:通过 Docker 和 Cypher 查询语言 运行图形数据库
Looking back at ResNet - a key step in the history of deep learning
Free and open source web version of Xshell [Happy New Year to everyone]









![[mysql chapter - advanced chapter] index](/img/b1/7231fa397e8b147235a20e7f97cd31.png)