这是 Rosetta Code: Balanced Brackets 的有效 Javascript

问题描述: https: //rosettacode.org/wiki/Balanced_brackets


出于某种原因,Freecodecamp 认为我的解决方案无法包含在他们的目录中,我只想确认一下https://forum.freecodecamp.org/t/additional-solution-for-rosetta-code-balanced-brackets/426226


我意识到,在平衡括号系统中,必须始终至少有一个子串等于,因为[]平衡括号需要相对的括号彼此面对,并且不能有空格。此外,可以重复删除所有实例,[]直到出现空字符串。


我在我能找到的所有测试用例上都尝试了这段代码,并且每次都有效。


function isBalanced(str) {

  while (true) {

    str = str.replace('[]', ''); 

    if(str.length==0){

      return true;

    }

    if(str[0]==']'||str[str.length-1]=='['){

      return false;

    }

  }

}


繁星淼淼
浏览 146回答 2
2回答

holdtom

它不仅是一种有效的方法,而且已经是 rosetta 代码 javascript 解决方案的一部分。平衡括号#ES5function isBalanced(str) {    var a = str, b    do { b = a, a = a.replace(/\[\]/g, '') } while (a != b)    return !a}

慕哥6287543

这是一个非正则表达式解决方案。const balanced = (string) => {&nbsp; let stack = [];&nbsp; for (let i = 0; i < string.length; i++) {&nbsp; &nbsp; const char = string[i];&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (char === '[') {&nbsp; &nbsp; &nbsp; &nbsp; stack.push('')&nbsp; &nbsp; } else if (char === ']') {&nbsp; &nbsp; &nbsp; &nbsp; stack.pop()&nbsp; &nbsp; }&nbsp; }&nbsp; return stack.length === 0;};[&nbsp; ['[]', true],&nbsp; ['[][]', true],&nbsp; ['[[][]]', true],&nbsp; ['][', false],&nbsp; ['][][', false],&nbsp; ['[]][[]', false]].forEach(([value, expected]) => {&nbsp; console.log(`balanced(${value}) === ${balanced(value)} expected ${expected}`);})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript