当前位置:网站首页>Understanding of stack and practical application scenarios
Understanding of stack and practical application scenarios
2022-07-28 13:51:00 【Maic】
StackIt's a data structure , stayjsWe know that , The basic data type is stored in stack memory , A reference data type is an address reference stored on the stack , It is actually stored in heap memory , Today we are going to seeleetcodesubject , Deepen the understanding of the stack , Match valid parentheses , This is the application of stack
The title means : Given one only includes '(',')','{','}','[',']' String s , Determines whether the string is valid .
requirement :
1、 Opening parentheses must be closed with closing parentheses of the same type
2、 The left parentheses must be closed in the correct order
The core of the topic is about Stack Usage scenarios of , And we can use stack to solve this problem
Let's get rid of this algorithm problem , What is stack? , Understanding stack , Use a diagram to understand
stay js We can use arrays to simulate Stack Characteristics , In and out of the stack , We often hear that the stack is first in and last out , Last in, first out , How to understand this seems to know , But it is always a concept of shell burning
We use an array to simulate the stack
Push
// Construct a stack structure , Define an array
var stack = [];
// Push
stack.push(1);
// Keep getting on the stack , Sometimes it is also called pressing stack
stack.push(2);
stack.push(3,4);
console.log(stack) // [1,2,3,4]
Out of the stack
...
let value = null;
value = stack.pop(); // 4 It bounced out
console.log(stack); // [1,2,3];
value = stack.pop(); // 3 It bounced out
console.log(stack); // [1,2];
value = stack.pop(); // 2 It bounced out
console.log(stack); // [1];
value = stack.pop(); // 1 It bounced out
console.log(stack); // []; // Finally, the length of the stack is empty
You can combine the above figure to understand the above code of stack entry and stack exit , When each stack out operation is performed , The arrays added later are popped out in turn . A more vivid metaphor is , The one who gets on the bus first sits on the tail of the bus , The one who got on the bus in the back , Standing at the door , When the car stops every time , Coming in the back , The one standing at the door went out first .
Get down to business , Understand the characteristics of stack structure , Then this problem can be solved by stack
const isValid = (s) => {
var stack = [];
for (let i=0;i<s.length;i++) {
const val = s[i]
// Into the stack,
if (val === '(') {
stack.push(')')
} else if (val === '[') {
stack.push(']'); // Into the stack,
} else if (val === '{') {
stack.push('}'); // Into the stack,
} else if (val !== stack.pop()) {
// pop Extract value , Compare the following in turn , If it is not equal to the extracted value , Then it's a mismatch , return false
return false;
}
}
return stack.length === 0 // All last pop Come out , Array is empty , Prove that all match
}
Is there any other solution besides this way ? Let's look at other ways
const isValid2 = (s) => {
const stack = [];
const map = new Map([
['(', ')'],
['[', ']'],
['{', '}']
]);
for (let i=0;i<s.length;i++) {
const c = s[i];
if (map.has(c)) {
// Judge map There is key value , Into the stack,
stack.push(c)
} else {
// Get the value of the stack
const mapKey = stack[stack.length -1];
// obtain map Value
if (map.get(mapKey) === c) {
stack.pop();
} else {
return false;
}
}
}
return stack.length === 0
}
summary
1、 Understand stack structure characteristics , First in, then out , Last in first out feature
2、 Array emulation stack feature ,push Push ,pop Out of the stack
3、 Application of symbol matching , Judge whether it is in the loop (,[,{, Then stack the corresponding symmetric symbol , Judge whether the current value is not equal to the stack value , Then the return false, until stackpop Find all the values , Stack length is empty , Prove that all symbols match .
4、 utilize map The symbols corresponding to the mapping match , Loop string , If map Yes key, Put the current key Add to stack , without , First, take out the corresponding stack key, Then use the current key, Go to map.get(key) Whether the obtained value is equal to the current value , If equal , Just pop The value cannot be found , If it's not equal, it goes back to false, Until the end of the cycle , The length of the stack is 0, Prove that all symbols match .
5、code example[1]
6、 Source of this question leetcode-20[2]
Reference material
[1]code example: https://github.com/maicFir/lessonNote/blob/master/leetcode/leetcode-20.js
[2]leetcode-20: https://leetcode.cn/problems/valid-parentheses/
边栏推荐
- POJ3268最短路径题解
- 30天刷题计划(三)
- Can second uncle cure young people's spiritual internal friction?
- Cool operation preheating! Code to achieve small planet effect
- Operator3-设计一个operator
- Paddleclas classification practice record
- Tutorial on the principle and application of database system (062) -- MySQL exercise questions: operation questions 32-38 (6)
- 了解BFC特性,轻松实现自适应布局
- R语言使用dpois函数生成泊松分布密度数据、使用plot函数可视化泊松分布密度数据(Poisson distribution)
- Facial expression recognition based on pytorch convolution - graduation project "suggestions collection"
猜你喜欢

Beyond istio OSS -- current situation and future of istio Service Grid

Strict mode -- let and const -- arrow function -- Deconstruction assignment -- string template symbol -- set and map -- generator function

You have to apologize if you get involved in the funny shop?

Half wave rectification light LED

基于神经网络的帧内预测和变换核选择

30天刷题训练(一)

最强分布式锁工具:Redisson
![[dark horse morning post] byte valuation has shrunk to $270billion;](/img/58/8d5c78d919ed60bc833ec4daa22e23.jpg)
[dark horse morning post] byte valuation has shrunk to $270billion; "Second uncle" video author responded to plagiarism; Renzeping said that the abolition of the pre-sale system of commercial housing

How to check if the interface cannot be adjusted? I didn't expect that the old bird of the 10-year test was planted on this interview question

SQL每日一练(牛客新题库)——第4天:高级操作符
随机推荐
Some thoughts on.Net desktop development
30 day question brushing plan (IV)
111. The sap ui5 fileuploader control realizes local file upload and encounters a cross domain access error when receiving the response from the server
DXF读写:标注样式组码中文说明
Paddleclas classification practice record
Socket类关于TCP字符流编程的理解学习
Beyond istio OSS -- current situation and future of istio Service Grid
Denial of service DDoS Attacks
[ecmascript6] function and its related use
JWT 登录认证 + Token 自动续期方案,写得太好了!
合并表格行---三层for循环遍历数据
I miss the year of "losing" Li Ziqi
数据库系统原理与应用教程(058)—— MySQL 练习题(二):单选题
R language ggplot2 visualization: use ggviolin function of ggpubr package to visualize violin diagram and set draw_ The quantiles parameter adds a specified quantile horizontal line (for example, 50%
Deployment之滚动更新策略。
面经整理,助力秋招,祝你称为offer收割机
org.apache.ibatis.exceptions.TooManyResultsException的异常排查过程
朋友发来几个面试题
《如何打一场数据挖掘赛事》入门版
最强分布式锁工具:Redisson