20. Valid Parentheses
LeetCode 20. Valid Parentheses
Description
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:
Example 2:
Example 3:
Tags
Stack, String
Solution
使用栈。遍历字符串,遇到任何左括号都将其入栈。如果遇到右括号,则检查栈顶是否是对应左括号,是则将该左括号弹出栈,否则返回false。最后如果栈为空则返回true,否则false。
Use a stack with capacity len(s)/2
. Traverse the string. If the current character is one of three kinds of left parenthesis then push it into the stack. Otherwise, the current character should be one of three kinds of right parenthesis. Check if it is match with the left parenthesis on the top of the stack. Pop the stack if it is. If it is not or the stack is empty, return false. At last, return true only if the stack is empty.
Complexity
Time complexity:
Space complexity:
Code
Last updated
Was this helpful?