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. 有效的括号 #4

Open
yankewei opened this issue Feb 28, 2020 · 0 comments
Open

20. 有效的括号 #4

yankewei opened this issue Feb 28, 2020 · 0 comments
Labels
字符串 题目类型为字符串 题目包含栈解法 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

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

有效字符串需满足:

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

示例 1:

输入: "()"
输出: true

示例 2:

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

示例 3:

输入: "(]"
输出: false

示例 4:

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

示例 5:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses

// 可以使用栈的概念来解决这种问题,判断最后栈是否为空
func isValid(s string) bool {
    dict := map[rune]rune{
        ')' : '(',
        ']' : '[',
        '}' : '{',
    }
    stack := []rune{}
    for _, v :=  range s {
        // 栈长度为0,则直接追加即可
        if len(stack) == 0 {
            stack = append(stack, v)
            continue
        }
        // 栈的最后一个元素和当前遍历的元素正好对应,则可以抵消,否则继续追加
        if stack[len(stack) - 1] == dict[v] {
            stack = stack[:len(stack) - 1]
        } else {
            stack = append(stack, v)
        }
    }
    return len(stack) == 0
}
@yankewei yankewei added 简单 题目难度为简单 字符串 题目类型为字符串 题目包含栈解法 labels Feb 28, 2020
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

1 participant