给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 注意空字符串可被认为是有效字符串。
- 链接:https://leetcode-cn.com/problems/valid-parentheses
示例 1: 输入: “()” 输出: true 示例 2: 输入: “()[]{}” 输出: true 示例 3: 输入: “(]” 输出: false
// 暴力法1var isValid = function(s) {const reg = /\(\)|{}|\[\]/while(s.match(reg)) {s = s.replace(reg, '')}return s === ''};// 暴力法2var 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;};// 都是把闭合的括号一直进行替换// 盏出盏进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};
