算法题-有效的括号【JS实现】

有效的括号


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

有效字符串需满足:

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

注意空字符串可被认为是有效字符串。
链接:https://leetcode-cn.com/problems/valid-parentheses

示例 1:

输入: “()” 输出: true
示例 2:

输入: “()[]{}” 输出: true
示例 3:

输入: “(]” 输出: false

暴力法:

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    
    
  const reg = /\(\)|{}|\[\]/
  while(s.match(reg)) {
    
    
    s = s.replace(reg, '')
  }
  return s === ''
};
var isValid = function (s) {
    
    
  while (s.length) {
    
    
    let temp = s;
    s = s.replace('()', '');
    s = s.replace('{}', '');
    s = s.replace('[]', '');
    if (s === temp) return false;
  }
  return true;
};

Stack:

var isValid = function(s) {
    
    
  if (s.length % 2 === 1) return false;
  const stack = [];
  const disc = ['()', '{}', '[]']
  const [leftReg, rightReg] = [/\(|{|\[/, /\)|}|\]/]
  for (let i of s) {
    
    
    if (i.match(leftReg)) {
    
    
      stack.push(i);
    }
    if (i.match(rightReg)) {
    
    
      if (disc.includes(stack[stack.length - 1] + i)) {
    
    
        stack.pop();
      } else {
    
    
        return false
      }
    }
  }
  return stack.length === 0
};
var isValid = function(s) {
    
    
  const stack = [];
  const map = {
    
    
    '(': ')',
    '[': ']',
    '{': '}',
  }
  for (let i of s) {
    
    
    if (map[i]) {
    
    
      stack.push(map[i])
    } else if (i !== stack.pop()) {
    
    
      return false;
    } 
  }
  return !stack.length
};

猜你喜欢

转载自blog.csdn.net/baidu_33591715/article/details/108470247