The target
1, stack for team leetcode-cn.com/problems/im… 2, the ball game leetcode-cn.com/problems/ba… 3, the backspace string leetcode-cn.com/problems/ba… 4, security stack sequence leetcode-cn.com/problems/va… 5, except for the outermost parentheses leetcode-cn.com/problems/re…
The stack for the team
class MyQueue {
constructor() {
this.left = []
this.right = []
}
push(x) {
this.left.push(x)
}
pop() {
while (this.left.length) this.right.push(this.left.pop())
const result = this.right.pop()
while (this.right.length) this.left.push(this.right.pop())
return result
}
peek() {
return this.left[0]}empty() {
return !this.left.length
}
}
Copy the code
The ball game
Simulation solution, according to the problem requirements to write code
var calPoints = function(ops) {
const len = ops.length;
const list = [];
for(let i = 0 ; i < len ; i++){
if(ops[i] === 'C'){
list.pop();
}else if(ops[i] === 'D') {const l = list.length;
list.push(list[l-1] * 2)}else if(ops[i] === '+') {const l = list.length;
list.push(list[l-1] + list[l-2])}else{
list.push(Number(ops[i]))
}
}
//console.log('list',list)
return list.reduce((a,b) = >a+b)
};
Copy the code
A string containing backspace
Using stack storage
Delete the last digit of the array
var backspaceCompare = function(s, t) {
let a = [];
for(let i = 0 ; i < s.length ; i++){
if(s[i] === The '#'){
a.pop()
}else{
a.push(s[i])
}
}
let b = [];
for(let i = 0 ; i < t.length ; i++){
if(t[i] === The '#'){
b.pop()
}else{
b.push(t[i])
}
}
return a.join(', ') === b.join(', ')};Copy the code
946. Validate stack sequence
Analog method, enumerated over and over
var validateStackSequences = function(pushed, popped) {
const list = [];
const len = pushed.length;
let idx = 0
for(let i = 0 ; i < len ; i++){
list.push(pushed[i]);
while(list.length > 0 && list[list.length-1] === popped[idx]){ idx++; list.pop(); }}return list.length === 0
};
Copy the code
Delete the outermost parentheses
Use of the stack
Use the variable to encounter the ‘(‘ record, more than 1 “(” must be off the outermost city layer ()
var removeOuterParentheses = function (s) {
let num = 0
let l = s.length
let redult = ' '
for (let i = 0; i < l; i++) {
if (s[i] == '(') {
if (++num > 1) {
redult += '('}}else {
if (--num > 0) {
redult += ') '}}}return redult
}
Copy the code