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


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

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("[{]}"));

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM