最近几天我一直在与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
一些评论:我知é�“我还没有检查这个例å�([])() ,但我想以æŸ�ç§�æ–¹å¼�将其拆分为两个较å°�的检查。
如æ�œæ‚¨è¯»åˆ°è¿™é‡Œï¼Œè°¢è°¢æ‚¨ã€‚我会感激任何形å¼�的指导,尽管我ä¸�希望有人替我解决这个问题。如æ�œæˆ‘过äº�å¤�æ�‚åŒ–äº†è¿™ä¸ªé—®é¢˜ï¼Œå› ä¸ºå®ƒæ˜¯ä¸€ä¸ª6级难度的问题,所以如何更è�ªæ˜�地解决它的æ��示将é��常å�—欢è¿�。
��致谢���