Skip to content

有效的括号

第一种

javascript
var isValid = function (s) {
  let arr = [];
  for (let i = 0; i < s.length; i++) {
    // 当前循环
    const start = s[i];
    if (s[i] == "(" || s[i] == "[" || s[i] == "{") {
      arr.push(s[i]);
    } else {
      //之前一次
      let end = arr[arr.length - 1];
      if (
        (start == ")" && end == "(") ||
        (start == "]" && end == "[") ||
        (start == "}" && end == "{")
      ) {
        arr.pop(s[i]);
      } else {
        return false;
      }
    }
  }
  return arr.length === 0;
};

第二种

javascript
var isValid = function (s) {
  let m = s.length;
  let map = new Map([
    ["{", "}"],
    ["[", "]"],
    ["(", ")"],
  ]);
  let stk = [];
  for (let ch of s) {
    if (map.has(ch)) {
      stk.push(ch);
    } else {
      if (map.get(stk[stk.length - 1]) !== ch || stk.length === 0) {
        return false;
      } else {
        stk.pop();
      }
    }
  }
  if (stk.length === 0) {
    return true;
  } else {
    return false;
  }
};
javascript
console.log(isValid("()"));
console.log(isValid("()[]{}"));
console.log(isValid("(]"));
console.log(isValid("([)]"));