【发布时间】:2020-06-23 22:33:52
【问题描述】:
过去几天一直在努力解决来自 codewars 的以下问题:
编写一个接受大括号字符串的函数,并确定大括号的顺序是否有效。如果字符串有效,它应该返回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
一些 cmets:我知道我仍然没有检查这个示例 ([])(),但我想以某种方式将它分成两个较小的检查。
感谢您阅读到此为止。尽管我不希望为我解决问题,但我会以某种方式感谢指导。由于这是一个 6kyu 问题,我可能在某种程度上过于复杂了,如果是这样,我将非常感谢有关如何更聪明地处理它的提示。
提前感谢您! :祈祷: :祈祷:
【问题讨论】:
-
你可能想多了。归结为推动左大括号并在看到右大括号时弹出,并查看它们是否匹配。
-
不确定这是否允许,但我在 youtube 频道上制作的最后一个视频正好解决了这个问题:youtube.com/watch?v=gQl3YrpHbkI&t=88s
-
这能回答你的问题吗? Algorithm: optimizing 'balancing brackets'
-
伙计们,请记住,OP 明确试图自己解决这个问题。指出答案或提供解决方案,尤其是过于复杂的解决方案,并不是他们想要的。
-
@DaveNewton 谢谢老兄!正是我希望的那种提示,我会尽力按照你的建议去做。
标签: javascript