题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
/** * * @param s string字符串 * @return bool布尔型 */ // 思路,利用栈结构;遍历字符串,只要当前val和栈顶不匹配,就push,匹配就pop,如果最后栈的长度==0,说明是匹配的 function isValid( s ) { let arr = [...s] let mystack = new myStack(); let reg = {'(':')',')':'(','{':'}','}':'{','[':']',']':'['} arr.forEach(val=>{ if(mystack.peak() == reg[val]){ mystack.pop() }else{ mystack.push(val) } }) return mystack.length() == 0?true:false } function myStack(str){ this.content = [] this.push = (val)=>{ this.content.push(val) } this.pop = ()=>{ return this.content.pop() } this.length = ()=>{ return this.content.length } this.init = (str)=>{ if(str) this.content = [...str] } this.peak = ()=>{ return this.content[this.content.length-1] } this.init(str) } module.exports = { isValid : isValid };