Skip to content

Commit 1ef7050

Browse files
committed
O(n) time and O(n) space for maintaining stack.
1 parent f007c0f commit 1ef7050

File tree

1 file changed

+37
-6
lines changed

1 file changed

+37
-6
lines changed
Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,47 @@
1+
"""
2+
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
3+
4+
An input string is valid if:
5+
6+
Open brackets must be closed by the same type of brackets.
7+
Open brackets must be closed in the correct order.
8+
Note that an empty string is also considered valid.
9+
10+
Example 1:
11+
12+
Input: "()"
13+
Output: true
14+
Example 2:
15+
16+
Input: "()[]{}"
17+
Output: true
18+
Example 3:
19+
20+
Input: "(]"
21+
Output: false
22+
Example 4:
23+
24+
Input: "([)]"
25+
Output: false
26+
Example 5:
27+
28+
Input: "{[]}"
29+
Output: true
30+
"""
131
class Solution:
232
def isValid(self, s: str) -> bool:
333
stack = []
434
mapping = {
5-
']':'[',
6-
'}':'{',
7-
')':'('
35+
']' : '[',
36+
'}' : '{',
37+
')' : '('
838
}
939
for char in s:
1040
if char in mapping.keys():
11-
top = stack.pop() if stack else '#'
12-
if mapping[char]!= top:
41+
top = stack.pop() if stack else '#' # if stack is empty and closing bracket comes. ex: '))'
42+
if mapping[char] != top:
1343
return False
1444
else:
1545
stack.append(char)
16-
return len(stack) == 0
46+
return len(stack) == 0
47+

0 commit comments

Comments
 (0)