File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ [Problem]
3+ https://leetcode.com/problems/valid-parentheses/
4+
5+ [Brainstorming]
6+ 1. 여는 괄호가 나올 경우에 Stack에 Push한다.
7+ 2. 닫는 괄호가 나왔을 경우에 Stack 가장 위에 여는 괄호와 일치 여부를 확인한다.
8+
9+ 이렇게 했을 때, 시간 복잡도는 O(N)으로 예상한다. (여기서 N은 s.length)
10+
11+ [Complexity]
12+ Time: O(N), N = s.length
13+ Space: O(N), N = stack.length
14+ """
15+ from os import popen
16+
17+
18+ class Solution :
19+ def isValid (self , s : str ) -> bool :
20+ bracket_dict = {'(' :')' , '{' :'}' , '[' :']' }
21+ stack = []
22+ for bracket in s :
23+ # 여는 괄호인 경우 Stack 추가
24+ if bracket in bracket_dict :
25+ stack .append (bracket )
26+ continue
27+
28+ # 닫는 괄호인 경우
29+ if not stack or bracket_dict [stack .pop ()] != bracket :
30+ return False
31+
32+ return not stack
33+
34+ sol = Solution ()
35+
36+ # Normal Case
37+ print (sol .isValid ("()" ) == True )
38+ print (sol .isValid ("()[]{}" ) == True )
39+ print (sol .isValid ("(]" ) == False )
40+ print (sol .isValid ("([])" ) == True )
41+ print (sol .isValid ("([)]" ) == False )
42+
43+ # Edge Case
44+ print (sol .isValid ("(" ) == False )
45+ print (sol .isValid ("]" ) == False )
46+
You can’t perform that action at this time.
0 commit comments