1. Description
Givian a string s containing just the characters '(', ')', '{', '}', '[', and ']', determine if the input string is valid.
An input string is valid if :
- Open bracket must be closed by the same type of brackets
- Open brackets must be closed in the correct order.
- Every closed bracket has a corresponding bracket of the same type.
constraints :
- 1 <= s.length <= \(10^4\)
- s consists of parentheses only '()[]{}'.
2. Algorithms
In this problem, the open bracket must be closed to the corresponding close bracket. So we can map all brackets into dictionary in key(open bracket) : value(close bracket).
The stack data structure will be used in this problem. For each element of the input string s, if the element is an open bracket, push the corresponding close bracket to stack. And if the element is an close bracket, check the last element of stack is same with the current close bracket.
s = "()[]{}", stack = []
iteration1 : s[i] = ( -> push to stack [')']
iteration2 : s[i] = ) -> check if the current element is same with stack[-1]
if True, pop the stack
- Start
- Declare variable named brackets
- Update key(open bracket) : value(close bracket) to brackets
- Declare variable named stack and initialize it to empty list(stack)
- Repeat the steps through the elements of s
- If the element is open bracket, push the corresponding close bracket to stack.
- If the element is close bracket, compare it to the last element of stack
- If there is any element in stack and two are same, pop the stack
- Else, return False
- Return if the length of stack is 0
- End
3. Codes
class Solution:
def isValid(self, s: str) -> bool:
brackets = {'(' : ')',
'{' : '}',
'[' : ']'}
stack = []
for c in s:
if c in brackets:
stack.append(brackets[c])
else:
if stack and c == stack[-1]:
stack.pop()
else:
return False
return len(stack) == 0
4. Conclusion
Time Complexity : \(O(N)\)
Space Complexity : \(O(1)\)
'Algorithm > Problems' 카테고리의 다른 글
[LeetCode] 14. Longest Common Prefix (0) | 2022.10.14 |
---|---|
[LeetCode] 13. Roman to Integer (0) | 2022.10.13 |
[LeetCode] 9. Palindrome Number (0) | 2022.10.13 |
[LeetCode] 1. Two Sum (0) | 2022.10.13 |