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!)", "()[]"));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…