数据结构和算法之堆栈应用:使用堆栈检查括号是否平衡
下面展示为栈 Stack
。
// 栈的定义: 先进后出
class Stack {
// 构造函数 dddd
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()
//Iterate through the string str
// 遍历str判断
for (const item of str) {
//For every closing parenthesis check for its opening parenthesis in stack
//因括号为成双成对的 故对于每个右括号,检查堆栈中的左括号
if([')',']','}'].includes(item)){
// If there is no data in the stack, it is an error. For example,
// the first input is a right parenthesis
// 如果栈里没有数据则为错误 例如:第一个输入的为右括号
if(myStack.isEmpty()) return false
// Out of stack and get out of stack characters
// 出栈且获取到出栈字符
let output = myStack.pop()
//If you can't find the opening parentheses for any closing one then returns false.
// 如果找不到任何右括号的左括号,则返回
// Note: output hundred percent be left parenthesis and item hundred percent
// be right parenthesis
// 注:output必然为左括号,item必然为右括号
// Array ['{}', '[]', '()'] and Array [')',']','}'] are three cases
// ['{}','[]','()']为三种情况 同上 [')',']','}']
if(!['{}','[]','()'].includes(output + item)) return false
}else{
// Otherwise, it is added to the stack
// 否则就添加进栈
myStack.push(item)
}
}
// If str in stack then also return false.
// Because every left and right bracket is corresponding and should be eliminated
// 字符在堆栈中,然后也返回false。 因为每一个左右括号都是对应的且应当合法消除的
if(!myStack.isEmpty) return false
// At the end return true if you haven't encountered any of the above false conditions.
// return true
// 如果没有遇到上述任何错误条件,则在结束时返回true。
return true
}
// 1、将str解构放进数组,便以使用forof
// 2、直接使用for循环
// ps:我这里使用的方法 1
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]))
/*
以下为输出结果
{[()]}
true
{[([({))]}}
false
{{]{}()()()}
false
{{(){}({[]})[]}}
true
*/
我比较懒 就写这么多 如有帮助,点个赞呗 😄 It’s my pleasure !THX!