如果所有括号在字符串中匹配,我应该打印支架匹配

时间:2017-04-23 20:42:30

标签: javascript jquery html string loops

  • 我是JavaScript的新手。
  • 我正在尝试编写逻辑,如果所有括号都匹配在一个只有括号的字符串中,如果所有括号都匹配则应打印bracket matched或如果括号不匹配则应bracket not matched
var bracketString = "((()()()))";
var match = true;

for (i = 0; i < bracketString.length; i++) {

        if (bracketString[i] === "(" && bracketString[i+1] === ")" ) {
            i++;
        } else if (bracketString[i] != "(" && bracketString[i+1] == ")" ) {
            i++;
        } else {
            i++;
            match = false;
        }

}

match ? console.log('Brackets matched') : console.log('Brackets not matched');

4 个答案:

答案 0 :(得分:1)

您需要使用计数器对开始和结束进行计数和匹配。您需要执行以下操作:

  1. 检查总数。 (的计数应等于)
  2. 总数应为偶数。
  3. 我们有两个柜台。
    1. 实际计数是( +1) -1的真实总和。
    2. 正常计数是()的当前总和(合法),但它不会低于0
    3. 仅当两个计数均为0时,括号才有效。
  4. 用例以及为什么我使用两个计数:

    ))((
    

    对于上述情况,计数将为:+2,而realCount将为0。所以这会失效。 这样,它不仅可以检查括号的数量,还可以检查括号的语义。因此有两个计数。

    <强>代码

    &#13;
    &#13;
    function validParentheses(parens) {
      var count = 0,
          realCount = 0;
      parens.split("").forEach(function(v) {
        if (v == "(") {
          count++;
          realCount++;
        } else if (v == ")") {
          count--;
          realCount--;
        }
        if (count < 0)
          count = 0;
      });
      return (count === 0 && realCount === 0);
    }
    
    console.log(validParentheses("(())"));
    console.log(validParentheses("()()"));
    console.log(validParentheses("))(("));
    &#13;
    &#13;
    &#13;

    聪明的方法

    我还可以提供另一种聪明的方法:

    &#13;
    &#13;
    function validParentheses(parens) {
      var indent = 0;
      // Go through the parentheses and do for each.
      // Keep checking the conditions on the way.
      for (var i = 0; i < parens.length && indent >= 0; i++) {
        indent += (parens[i] == '(') ? 1 : -1;
      }
      // If it's 0, then good.
      return (indent == 0);
    }
    
    console.log(validParentheses("(())"));
    console.log(validParentheses("()()"));
    console.log(validParentheses("))(("));
    &#13;
    &#13;
    &#13;

答案 1 :(得分:1)

当您看到(时,只需循环播放字符串即可添加到计数器,并在看到)时将其从中删除。如果结果不是0,则它们不匹配:

function check(str) {
  var open = 0;
  for (var n = 0; n < str.length; ++n) {
    var ch = str[n];
    if (ch === '(') {
      ++open;
    } else if (ch === ')' && --open < 0) {
      return false; // Got ) with no corresponding (
    }
  }
  return open === 0;
}
function test(str) {
  console.log(str, check(str));
}
test("((()()()))");
test("((()");
test("()))");
test(")())");
test("()");
test("x");

答案 2 :(得分:0)

使用String.prototype.match()创建数组的方法。如果其他字符也在字符串

中可以工作

shift()splice()删除配对,直到没有留下或发现不匹配为止

function isMatching(str) {
  // create array of only parentheses
  var braces = str.match(/\(|\)/g);
  // must at least have pairs, but even if they aren't matches will be caught below
  var hasPairs = braces.length %2 === 0;

  while (braces.length && hasPairs) {
    // close can't precede open.
    // a close is removed removed from array when open is found
    // so at any point in this loop if first element in array is `)` it is a mismatch
    if (braces.shift() === ')') break;

    // we have an open, look for first close
    var closeIdx = braces.indexOf(')');

    // if no close for this open, get out of here
    if (closeIdx === -1) break;

    //or remove matching close
    braces.splice(closeIdx, 1);
  }
  // combination of `shift()` and `splice()` above will remove each pair
  //  any break above would leave elements in array due to mismatch
  return !braces.length;
}

logMatch("(()")
logMatch("((()()()))")
logMatch("(())");
logMatch("()()");
logMatch(")(()");

function logMatch(str){
   console.log(str, isMatching(str))
}

我迟到了,但这是一个很好的练习

答案 3 :(得分:-2)

var bracketString = "((()()()))";
var counter=0;

for (i = 0; i < bracketString.length; i++) {

    if (bracketString[i] === "(") {
        counter++;
    } else if (bracketString[i] === ")" ) {
        counter --;
    } 
    if (counter < 0){
        console.log('Brackets mismatched'); // for example ())(
        break;
    }
}

if (counter==0){
   console.log('Brackets matched');
}

else if (counter>0){
   console.log('Brackets mismatched');
}
/* we don't consider counter<0 because before getting out of the for it passes 
this validation. */