20. Valid Parentheses

83 阅读1分钟

20. Valid Parentheses

难度简单3533

\

利用 stack FILO 将 '[]' '()' '{}' 转化为 key value 结构进行验证

执行步骤

  1. 按序取出字母 charKeyOrValue
  2. 如果是有效的 key 就 push 进 keyStack
  3. 如果是有效的 value 就进行验证 keyStack pop出key并取出相应的value ,如果 charKeyOrValue 与 value相等就进入下一次循环否则直接返回false
  4. 循环完了如果满足 keyStack.length === 0就说明是正确的
const isValid = function (s) {
    const keyStack = [] // ['({[']
    const keyValueMap = new Map([
        ['(', ')'],
        ['[', ']'],
        ['{', '}'],
    ])
    for (let i = 0; i < s.length; i++) {
        const charKeyOrValue = s[i]
        const isValidKey = keyValueMap.has(charKeyOrValue)
        if(isValidKey) {
           keyStack.push(charKeyOrValue)
        } else {
           const key = keyStack.pop() 
           const value = keyValueMap.get(key)
           const isValidValue = value === charKeyOrValue
           if(isValidValue) {
               continue
           } else {
               return false
           }
        }
    }
    return keyStack.length === 0
};