feat(0020_valid-parentheses): add py3 soln
This commit is contained in:
parent
7bf796913f
commit
5820974811
29
0020_valid-parentheses/README.md
Normal file
29
0020_valid-parentheses/README.md
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid.
|
||||||
|
|
||||||
|
An input string is valid if:
|
||||||
|
|
||||||
|
1. Open brackets must be closed by the same type of brackets.
|
||||||
|
2. 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 `'()[]{}'`.
|
30
0020_valid-parentheses/python3/solution.py
Normal file
30
0020_valid-parentheses/python3/solution.py
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
from collections import deque
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
bracket_pairing = {
|
||||||
|
'{': '}',
|
||||||
|
'[': ']',
|
||||||
|
'(': ')'
|
||||||
|
}
|
||||||
|
|
||||||
|
closing_brackets = tuple(bracket_pairing.values())
|
||||||
|
|
||||||
|
def is_matching_pair(self, opening, closing):
|
||||||
|
return self.bracket_pairing[opening] == closing
|
||||||
|
|
||||||
|
def isValid(self, s: str) -> bool:
|
||||||
|
stack = deque()
|
||||||
|
|
||||||
|
for c in s:
|
||||||
|
if c in self.closing_brackets:
|
||||||
|
try:
|
||||||
|
last_char = stack.pop()
|
||||||
|
except IndexError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
if not self.is_matching_pair(last_char, c):
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
stack.append(c)
|
||||||
|
|
||||||
|
return len(stack) == 0
|
Loading…
Reference in New Issue
Block a user