Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

20. 有效的括号 #26

Open
GpingFeng opened this issue Dec 26, 2020 · 1 comment
Open

20. 有效的括号 #26

GpingFeng opened this issue Dec 26, 2020 · 1 comment

Comments

@GpingFeng
Copy link
Owner

20. 有效的括号

可以根据栈来解决,根据先进后出的原则,当匹配到是闭合括号时,出栈的总应该是和它相匹配的,否则就是非法的

var isValid = function(s) {
    let stack = [];
    for(let i of s) {
        let target = stack[stack.length - 1];
        if ((i === ')' && target === '(') || 
        (i === ']' && target === '[') ||
        ((i === '}' && target === '{'))) {
            stack.pop();
            continue;
        }
        stack.push(i);
    }
    return stack.length === 0;
}

复杂度分析

  • 时间复杂度——O(n)
  • 空间复杂度——O(n)
@GpingFeng
Copy link
Owner Author

栈 + Map

跟上面一样,只是多加一个 map 结构存储

var isValid = function(s) {
    // 由题目可以发掘我们可以利用栈的先进后出特性来解决这个问题
    // 定义一个常量记录括号的信息
    if (s.length % 2 !== 0) return false;
    const mapBrackets = {
      '(': -1,
      ')': 1,
      '{': -2,
      '}': 2,
      '[': -3,
      ']': 3
    }
    let stack = []
    for (let i = 0; i < s.length; i++) {
      let cur = mapBrackets[s[i]]
      if (cur < 0) {
        stack.push(cur)
      } else {
        if (cur + stack.pop() !== 0) {
          return false
        }
      }
    }
    if (stack.length > 0) {
      return false
    }
    return true
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant