leetcode25

128 阅读1分钟

题目

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

有效字符串需满足:

左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。

题目分析

最好的方法是利用栈的数据结构来解决这个问题,也算是比较经典的解法。
先定义好一个hashmap

    const map = new Map([
      [')', '('],
      ['}', '{'],
      [']', '['],
    ])

在定义一个空数组,依次遍历字符串,如果匹配到了就消除该元素。循环结束如果数组依旧为空,则所有括号都得到了匹配,返回true,否则返回false。

代码

var isValid = function(s) {
    const map = new Map([
      [')', '('],
      ['}', '{'],
      [']', '['],
    ])
    const stack = []
    for(let i = 0; i < s.length; i ++) {
      if(stack.length) {
        if(stack[stack.length - 1] === map.get(s[i])) {
          stack.pop()
        } else {
          stack.push(s[i])
        }
      } else {
        stack.push(s[i])
      }
    }
    if(stack.length) {
      return false
    }
    return true
};