File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ 20. Valid Parentheses
3+ https://leetcode.com/problems/valid-parentheses/description/
4+
5+ Solution
6+ Uses a stack to check if the parentheses are valid.
7+
8+ 1. Initialize an empty stack.
9+ 2. Iterate through each character in the string.
10+ 3. If the character is an opening parenthesis,
11+ push it to the stack.
12+ 4. If the character is a closing parenthesis,
13+ pop the stack and check if the opening parenthesis matches.
14+ 5. If the stack is empty, return True.
15+ 6. Otherwise, return False.
16+
17+ Time complexity: O(n)
18+ Space complexity: O(n)
19+ """
20+
21+
22+ class Solution :
23+ def isValid (self , s : str ) -> bool :
24+ stack = ""
25+ opening = ["(" , "[" , "{" ]
26+ closing = [")" , "]" , "}" ]
27+
28+ for _s in s :
29+ if _s in opening :
30+ stack = _s + stack
31+ else :
32+ if stack :
33+ if opening [closing .index (_s )] == stack [0 ]:
34+ stack = stack [1 :]
35+ else :
36+ return False
37+ else :
38+ return False
39+
40+ if len (stack ) > 0 :
41+ return False
42+ else :
43+ return True
You can’t perform that action at this time.
0 commit comments