gpt4 book ai didi

javascript - 如何检查javascript中的有效大括号,编程问题?

转载 作者:行者123 更新时间:2023-12-01 15:39:50 24 4
gpt4 key购买 nike

过去几天一直在努力解决代码战中的以下问题:
编写一个接受大括号字符串的函数,并确定大括号的顺序是否有效。它应该返回 true如果字符串有效,并且 false如果它无效。
所有输入字符串都是非空的,并且只包含圆括号、方括号和花括号:()[]{} .
什么被认为是有效的?
如果所有大括号都与正确的大括号匹配,则认为一串大括号是有效的。
例子

"(){}[]"   =>  True
"([{}])" => True
"(}" => False
"[(])" => False
"[({})](]" => False
所以我真的坚持使用这个代码,这就是我到目前为止所拥有的:
function validBraces(braces){
let opening = [ '(', '[', '{']
let closing = [ ')', ']', '}']
let count = 0
const left = []
const right = []

// I generate left and right arrays, left w/the opening braces from the input, right w/ the closing
for (let i = 0; i < braces.length; i++) {
if (opening.includes(braces[i])) {
left.push(braces[i])
} else if (closing.includes(braces[i])) {
right.push(braces[i])
}
}
if (braces.length % 2 !== 0) {
return false
}
// I know there's no point in doing this but at one point I thought I was finishing the program and thought I would 'optimize it' to exit early, probably this is dumb haha.
if (left.length !== right.length) {
return false
}
// The juicy (not juicy) part where I check if the braces make sense
for (let i = 0; i < left.length; i++) {
// If the list are made up of braces like ()[]{} add one to counter
if (opening.indexOf(left[i]) === closing.indexOf(right[i])) {
count += 1
} else // If left and right are mirrored add one to the counter
if (opening.indexOf(left[i]) === closing.indexOf(right.reverse()[i])) {
count += 1
}
}
//If the counter makes sense return true
if (count === braces.length / 2) {
return true
} else { return false}
}


console.log(validBraces( "()" )) //true
console.log(validBraces("([])")) //true
console.log(validBraces( "[(])" )) //false
console.log(validBraces( "[(})" )) //false
console.log(validBraces( "[([[]])]" )) //true

一些评论:我知道我仍然没有检查这个例子 ([])() 但我想以某种方式将它分成两个较小的检查。
谢谢你读到这里。尽管我不希望为我解决问题,但我会以某种方式感谢指导。由于它是一个 6kyu 问题,我可能在某种程度上过于复杂了,如果是这样,关于如何更聪明地处理它的提示将非常感激。
先感谢您! :祈祷::祈祷:

最佳答案

hell 耶!!我很高兴最终自己使用这里给我的一些提示找到了解决方案:

function validBraces(braces){
let opening = [ '(', '[', '{']
let closing = [ ')', ']', '}']
let arr = []
//console.log(closing.indexOf(braces[")"]) === opening.indexOf(arr[")"]))
for (let i = 0; i < braces.length; i++) {
if (opening.includes(braces[i])) {
arr.push(braces[i])
} else
if (closing.indexOf(braces[i]) === opening.indexOf(arr[arr.length - 1])) {
arr.pop()
} else return false
} return arr.length === 0;
}

显然我一开始就想多了哈哈。感谢所有帮助过的人!

关于javascript - 如何检查javascript中的有效大括号,编程问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62544776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com