Skip to content

LeetCode 20. 有效的括号 #13

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

Open
Chocolate1999 opened this issue Sep 13, 2020 · 2 comments
Open

LeetCode 20. 有效的括号 #13

Chocolate1999 opened this issue Sep 13, 2020 · 2 comments
Labels
数据结构-栈

Comments

@Chocolate1999
Copy link
Owner

仰望星空的人,不应该被嘲笑

题目描述

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

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

输入: "()[]{}"
输出: true

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

输入: "{[]}"
输出: true

题解

发现越靠后的左括号,最先匹配,也就是后进先出的思想,于是考虑使用栈这个数据结构。

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
  // 如果是奇数,不可能匹配成功,直接返回false
  if(s.length & 1) return false
  let stack = []
  for(let i=0;i<s.length;i++){
    if(s[i] === '(' || s[i] === '{' || s[i] === '[') stack.push(s[i])
    else if(s[i] === ')' && stack[stack.length-1] === '(') stack.pop()
    else if(s[i] === '}' && stack[stack.length-1] === '{') stack.pop()
    else if(s[i] === ']' && stack[stack.length-1] === '[') stack.pop()
    else return false
  }
  return !stack.length
};

最后

文章产出不易,还望各位小伙伴们支持一波!

往期精选:

小狮子前端の笔记仓库

访问超逸の博客,方便小伙伴阅读玩耍~

学如逆水行舟,不进则退
@Chocolate1999 Chocolate1999 added the 数据结构-栈 label Sep 13, 2020
@Chocolate1999
Copy link
Owner Author

2022/2/7

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function (s) {
    let arr = [];
    for (let ch of s) {
        let ans = arr[arr.length - 1];
        if (ch === '(' || ch === '{' || ch === '[') arr.push(ch);
        else if (ch === ')' && ans === '(' || ch === '}' && ans === '{' || ch === ']' && ans === '[') arr.pop();
        else arr.push(ch);
    }
    return arr.length === 0;
};

@HearLing
Copy link

HearLing commented Feb 7, 2022

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    const map = {'(':')','{':'}','[':']'}
    const result = [s[0]];
    for(let i =1;i<s.length;i++){
        if(map[result[result.length-1]] === s[i]){
            result.pop()
        }
        else {
            result.push(s[i])
        }
    }
    return result.length===0
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
数据结构-栈
Projects
None yet
Development

No branches or pull requests

2 participants