题目描述
Given a string s 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.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Constraints:
1 <= s.length <= 104
s consists of parentheses only '()[]{}'.
自己的解法
Facing pairing problem, it is very natural to use a stack. Because stack can easily store stuffs and pop them out to construct a closest pair.
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# if str == "":
# return True
stack = ""
for i in range(len(str)):
if str[i] in "([{":
stack += str[i]
elif stack == "":
return False
elif not stack[-1] + str[i] in ["()","[]","{}"]:
return False
return stack == ""
The time complexity is O ( n ) O(n) O(n) and the space complexity is O ( 1 ) O(1) O(1).
参考答案
Same idea with some trick to shorten the code. Here we just pass.
总结
- 简单的一题,提醒我们面对pair问题使用stack。