I have this codewars exercise in which I have to write a piece of code to validate that a supplied string is balanced.
(我进行了代码战练习,其中我必须编写一段代码来验证所提供的字符串是否平衡。)
For example, I need to make sure when I encounter an opening "("
then I'll have to make sure there's also closing ")"
tag. (例如,我需要确保在遇到打开的"("
必须确保也关闭了")"
标记。)
However, in this code, a second string will contain the parentheses or characters for the first string to find and check. (但是,在此代码中,第二个字符串将包含要查找和检查的第一个字符串的括号或字符。)
Here is my code:
(这是我的代码:)
function isBalanced(s, caps) {
let strArr = s.split("");
let capsArr = caps.split("");
let pairsCaps = caps.match(/.{1,2}/g);
for(let i = 0; i < strArr.length; i++) {
for (let m = 0; m < pairsCaps.length; m++){
if(strArr[i] == pairsCaps[m][0] && strArr[strArr.length -1] == pairsCaps[m][1]) {
return true;
} else {
return false;
}
}
}
}
console.log(isBalanced("Sensei says -yes-!", "--"));
However, when I ran some sample tests, I found out that while it worked for isBalanced("(Sensei says yes!)", "()")
and isBalanced("(Sensei [says] yes!)", "()[]")
, the code wasn't working when there's --
in isBalanced("Sensei says -yes-!", "--")
in which it returned false
when it was supposed to return true
.
(但是,当我运行一些示例测试时,我发现它适用于isBalanced("(Sensei says yes!)", "()")
和isBalanced("(Sensei [says] yes!)", "()[]")
当有代码是行不通的--
在isBalanced("Sensei says -yes-!", "--")
在它returned false
时,它应该return true
。)
I looked over my code but couldn't narrow down the problem.
(我查看了我的代码,但无法缩小问题的范围。)
Please help...? (请帮忙...?)
ask by Kristina Bressler translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…