給定一個只包括 '(',')','{','}','[',']' 的字符串,判斷字符串是否有效。


使用字符的一個一個判斷處理

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