有效括号

给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合

栈法


var isValid = function (s) {
  const rightMap = new Map([
    ["(", ")"],
    ["[", "]"],
    ["{", "}"],
  ]);
  let stack = [];
  for (let index = 0; index < s.length; index++) {
    const element = s[index];
    switch (element) {
      case "{":
      case "[":
      case "(":
        stack.push(element);
        break;
      default: {
        if (stack.length === 0) {
          return false;
        }
        let leftValue = stack.pop();
        if (rightMap.get(leftValue) !== element) {
          return false;
        }
      }
    }
  }
  return stack.length === 0;
};
isValid("()");

正则匹配


var isValid = function(s) {
  let len
  do {
    len = s.length
    s = s.replace(/\(\)|\[\]|\{\}/g, '')
  } while (len !== s.length)
  return !s.length
};

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦