数据结构和算法之堆栈应用:使用堆栈检查括号是否平衡
下面展示为栈 Stack 。
class Stack {
constructor(){
this.arr = [];
}
push(element){
this.arr.push(element);
}
pop() {
return this.arr.pop();
}
isEmpty(){
if(this.arr.length < 1) return true
else return false
}
}
下面展示实现代码 codes 。
function checkStr(str){
let myStack = new Stack()
for (const item of str) {
if([')',']','}'].includes(item)){
if(myStack.isEmpty()) return false
let output = myStack.pop()
if(!['{}','[]','()'].includes(output + item)) return false
}else{
myStack.push(item)
}
}
if(!myStack.isEmpty) return false
return true
}
var ssr= "{[()]}"
console.log(ssr)
console.log(checkStr([...ssr]))
ssr = "{[([({))]}}"
console.log(ssr)
console.log(checkStr([...ssr]))
ssr = "{{]{}()()()}"
console.log(ssr)
console.log(checkStr([...ssr]))
ssr = "{{(){}({[]})[]}}"
console.log(ssr)
console.log(checkStr([...ssr]))
我比较懒 就写这么多 如有帮助,点个赞呗 😄 It’s my pleasure !THX!
|