目标
1、化栈为队 leetcode-cn.com/problems/im…
2、球比赛 leetcode-cn.com/problems/ba…
3、较含退格的字符串 leetcode-cn.com/problems/ba…
4、证栈序列 leetcode-cn.com/problems/va…
5、除最外层的括号 leetcode-cn.com/problems/re…
化栈为队
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
}
}
复制代码
球比赛
模拟解决,根据题目要求写代码即可
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)
};
复制代码
较含退格的字符串
利用栈存储
遇到#删除数组最后一位即可
var backspaceCompare = function(s, t) {
let a = [];
for(let i = 0 ; i < s.length ; i++){
if(s[i] === '#'){
a.pop()
}else{
a.push(s[i])
}
}
let b = [];
for(let i = 0 ; i < t.length ; i++){
if(t[i] === '#'){
b.pop()
}else{
b.push(t[i])
}
}
return a.join(',') === b.join(',')
};
复制代码
946. 验证栈序列
模拟法,一遍枚举过
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
};
复制代码
1021. 删除最外层的括号
利用栈
使用变量将遇到的'('记录下来,超出1个"("必然可以脱去最外城层()
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
}
复制代码