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. Valid Parentheses #20

Open
yunshuipiao opened this issue Jun 5, 2019 · 0 comments
Open

20. Valid Parentheses #20

yunshuipiao opened this issue Jun 5, 2019 · 0 comments

Comments

@yunshuipiao
Copy link
Owner

20. Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true
Example 3:

Input: "(]"
Output: false
Example 4:

Input: "([)]"
Output: false
Example 5:

Input: "{[]}"
Output: true

解法

简单题目,借助栈来保存即可。要注意有亮点:

  1. 当前字符必须和栈顶字符匹配
  2. 假设字符为 "( { [ [ } )", 栈中保存的为 "[ [ "。因此最后需要判断栈是否为空。
fun isValid(s: String): Boolean {
    val map = hashMapOf('(' to ')', '{' to '}', '[' to ']')
    val result = ArrayList<Char>()
    for (c in s) {
        println(c)
        if (c in map.keys) {
            result.add(c)
        } else {
            if (result.isEmpty() || map[result.last()] != c) {
                return false
            } else {
                result.removeAt(result.size - 1)
            }
        }
    }
    return result.isEmpty()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant