FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

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

Open lgwebdream opened this issue 5 years ago • 2 comments

/*
  有效字符串需满⾜:
 	 	1. 左括号必须⽤相同类型的右括号闭合。
  	2. 左括号必须以正确的顺序闭合。
  注意空字符串可被认为是有效字符串。
  示例1:
  	输⼊: "()"
  	输出: true
  示例2:
  	输⼊: "()[]{}"
  	输出: true
  示例 3:
  	输⼊: "(]"
  	输出: false
  示例 4:
  	输⼊: "([)]"
  	输出: false
  示例 5:
  	输⼊: "{[]}"
  	输出: true
*/

lgwebdream avatar Jul 06 '20 16:07 lgwebdream

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

lgwebdream avatar Jul 06 '20 16:07 lgwebdream

function fn(str) {
  const stack = []
  const leftMap = {
    '(': ')',
    '[': ']',
    '{': '}'
  }
  const rightMap = {
    ')': '(',
    ']': '[',
    '}': '{'
  }
  let cur
  for (let i = 0; i < str.length; i++) {
    cur = str[i]
    if (leftMap[cur]) {
      stack.push(cur)
    } else if (rightMap[cur]) {
      if (!stack.length) return false
      if (stack.pop() !== rightMap[cur]) return false
    }
  }
  return true
}
console.log(fn('()'));        // true
console.log(fn('()[]'));      // true
console.log(fn('()[]{}'));    // true
console.log(fn('(]'));        // false
console.log(fn('([)]'));      // false
console.log(fn('{[]}'));      // true

AAA611 avatar Aug 26 '22 08:08 AAA611