Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

javascript - 平衡字符Javascript(Balanced Characters Javascript)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code currently, when an opening tag is found, only checks to see if the final character in the string is the matching closing tag:(当前,您的代码在找到开始标记时仅检查字符串中的最后一个字符是否为匹配的结束标记:)

if(strArr[i] == pairsCaps[m][0] && strArr[strArr.length -1] == pairsCaps[m][1]) { That's like saying "If the character being iterated over is ( , check to see that the last character is ) ".(这就像说“如果要迭代的字符是( ,请检查最后一个字符是) ”。) One option is to create a stack of currently open tags instead.(一种选择是改为创建一堆当前打开的标签。) When you find an opening tag, push it to the tag stack;(当您找到一个开始的标签时,将其推入标签堆栈。) when you find a closing tag, remove the top item from the tag stack if it matches.(当找到结束标签时,如果标签匹配,则从标签堆栈中删除最上面的项目。) (If it doesn't match, the tags are unbalanced).((如果不匹配,则标签不平衡)。) If the stack has any elements in it at the end, the tags are unbalanced.(如果堆栈末尾有任何元素,则标签不平衡。) Otherwise, it's balanced.(否则,它是平衡的。) Another option is to construct a regular expression which matches an opening tag, followed by non-tag characters, followed by the closing tag.(另一种选择是构造一个正则表达式,该正则表达式匹配一个开始标签,然后是非标签字符,然后是结束标签。) Repeatedly replace the match substring with nothing until the pattern doesn't match anymore, and check to see if the final result is the empty string:(重复将match子字符串替换为空,直到模式不再匹配为止,并检查最终结果是否为空字符串:) // https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript const escape = s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); function isBalanced(s, caps) { const openTags = []; const closeTags = []; for (const [index, char] of [...caps].entries()) { (index % 2 ? closeTags : openTags).push(char); } const pattern = new RegExp( openTags .map((openTag, i) => `${escape(openTag)}[^${escape(caps)}]*${escape(closeTags[i])}`) .join('|') ); let str = s; let lastStr; while (lastStr !== str) { lastStr = str; str = str.replace(pattern, ''); } return str.replace(new RegExp(`[^${caps}]*`), '') === ''; } console.log(isBalanced("Sensei says -yes-!", "--")); console.log(isBalanced("(Sensei says yes!)", "()")) console.log(isBalanced("(Sensei [says] yes!)", "()[]")); console.log(isBalanced("(Sensei [says] yes!", "()[]")); console.log(isBalanced("Sensei [says] yes!)", "()[]"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...