You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
let map={
'}':'{',
']':'[',
')':'(',
}
function fn(str){
let stack = []
let stack2 = []
let res = {}
for(let i = 0;i<str.length;i++){
let c = str.charAt(i)
if(['{','(','[',')',']','}'].includes(c)){
if(['{','(','['].includes(c)){
let it = i+'-'+c
stack.push(c)
stack2.push(it)
}else if(stack.length&&stack[stack.length-1]!==map[c]){
let k = stack.length-1
while(stack[k]!==map[c]){
k--
}
stack.splice(k,1)
stack2.splice(k,1)
}else if(stack.length&&stack[stack.length-1]===map[c]){
stack.pop()
stack2.pop()
}
}
}
stack2.map(it=>{
let list = it.split('-')
res[list[0]] = list[1]
})
return res
}
console.log(fn('${{(3+5)*2+(5/(24)}'))
Activity
sisterAn commentedon Jan 25, 2021
解答:利用栈结构
解题思路: 将字符串中的字符依次入栈,遍历字符依次判断:
{、(、[,直接入栈}、)、]中的一种,({, 如果继续遍历到的元素为), 那么当前元素序列为({)是不可能有效的,所以此时与出栈元素匹配失败,将出栈元素写进结果数组,并继续匹配当前元素当遍历完成时,所有已匹配的字符都已匹配出栈,如果栈不为空,说明字符串中还有未匹配的左括号字符,则将栈元素直接写进结果数组
代码实现:
时间复杂度:O(n)
空间复杂度:O(n)
相关题目:图解腾讯&哔哩哔哩&leetcode20:有效的括号
xllpiupiu commentedon Oct 6, 2021
AlexZhang11 commentedon May 24, 2024
let map={ '}':'{', ']':'[', ')':'(', } function fn(str){ let stack = [] let stack2 = [] let res = {} for(let i = 0;i<str.length;i++){ let c = str.charAt(i) if(['{','(','[',')',']','}'].includes(c)){ if(['{','(','['].includes(c)){ let it = i+'-'+c stack.push(c) stack2.push(it) }else if(stack.length&&stack[stack.length-1]!==map[c]){ let k = stack.length-1 while(stack[k]!==map[c]){ k-- } stack.splice(k,1) stack2.splice(k,1) }else if(stack.length&&stack[stack.length-1]===map[c]){ stack.pop() stack2.pop() } } } stack2.map(it=>{ let list = it.split('-') res[list[0]] = list[1] }) return res } console.log(fn('${{(3+5)*2+(5/(24)}'))