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

使用字符的一个一个判断处理

const obj = {
      '{': "}",
      '(': ")",
      '[': "]",
 
    }
    function isValid(str) {
      const len = str.length
      let index = 0
      if (len % 2 !== 0) {
        return false
      }
      const mid = len / 2
      while (index < mid) {
        if (obj[str[index]] === str[len - 1 - index]) {
          index++
          continue
        }
        if (obj[str[index]] === str[index + 1]) {
          index += 2
          continue
        }
        return false
      }
      return true
    }
 
    console.log(isValid("[{]}"));

 

posted @ 2020-11-09 11:07  王室  阅读(739)  评论(0编辑  收藏  举报