当前位置:网站首页>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/
边栏推荐
- R language uses LM function to build linear regression model and subset function to specify subset of data set to build regression model (use floor function and length function to select the former pa
- 30 day question brushing plan (II)
- POJ3275 Ranking the Cows题解
- 掌握常见的几种排序-选择排序
- Operator3-设计一个operator
- No swagger, what do I use?
- R language Visual scatter diagram, geom using ggrep package_ text_ The repl function avoids overlapping labels between data points (add labels to specific areas of the visual image using the parameter
- Graph traversal (BFS & DFS basis)
- Generation of tables and contingency tables (cross tables) of R language factor data: use the summary function to analyze the list, view the chi square test results, and judge whether the two factor v
- R language uses LM function to build multiple linear regression model, writes regression equation according to model coefficient, and uses conflict function to give 95% confidence interval of regressi
猜你喜欢

Use non recursive method to realize layer traversal, preorder traversal, middle order traversal and post order traversal in binary tree

酷炫操作预热!代码实现小星球特效

After finishing, help autumn move, I wish you call it an offer harvester

在 Kubernetes 中部署应用交付服务(第 1 部分)

Product Manager: job responsibility table

算法---不同路径(Kotlin)

30 day question brushing plan (II)

How to play a data mining game entry Edition

No swagger, what do I use?

Intra prediction and transform kernel selection based on Neural Network
随机推荐
Strict mode -- let and const -- arrow function -- Deconstruction assignment -- string template symbol -- set and map -- generator function
R语言检验样本比例:使用prop.test函数执行单样本比例检验计算总体中成功样本比例p值的置信区间(设置conf.level参数指定置信水平、置信区间的大小)
Jenkins -- continuous integration server
Force buckle 2354. Number of high-quality pairs
C language: random number + quick sort
Some thoughts on.Net desktop development
力扣 2354. 优质数对的数目
R语言使用lm函数构建线性回归模型、使用subset函数指定对于数据集的子集构建回归模型(使用floor函数和length函数选择数据前部分构建回归模型)
Analyzing the principle of DNS resolution in kubernetes cluster
我秃了!唯一索引、普通索引我该选谁?
DOJNOIP201708奶酪题解
Poj3275 ranking the cows
JWT login authentication + token automatic renewal scheme, well written!
[Architecture] reading notes of three micro service books with high scores
Volcanic stone investment Zhang Suyang: hard technology, the relatively certain answer in the next 10 years
C语言:归并排序
【C语言】结构体指针与结构体变量作形参的区别
面经整理,助力秋招,祝你称为offer收割机
Tutorial on the principle and application of database system (059) -- MySQL exercise questions: operation questions 1-10 (III)
数据库系统原理与应用教程(058)—— MySQL 练习题(二):单选题