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+
16+ class Solution :
17+ def isValid (self , s : str ) -> bool :
18+ bracket_dict = {'(' :')' , '{' :'}' , '[' :']' }
19+ stack = []
20+ for bracket in s :
21+ # 여는 괄호인 경우 Stack 추가
22+ if bracket in bracket_dict :
23+ stack .append (bracket )
24+ # 닫는 괄호인 경우
25+ else :
26+ if not stack :
27+ return False
28+ if bracket_dict [stack .pop ()] != bracket :
29+ return False
30+
31+ return not stack
32+
33+ sol = Solution ()
34+
35+ # Normal Case
36+ print (sol .isValid ("()" ) == True )
37+ print (sol .isValid ("()[]{}" ) == True )
38+ print (sol .isValid ("(]" ) == False )
39+ print (sol .isValid ("([])" ) == True )
40+ print (sol .isValid ("([)]" ) == False )
41+
42+ # Edge Case
43+ print (sol .isValid ("(" ) == False )
44+ print (sol .isValid ("]" ) == False )
45+
46+
You can’t perform that action at this time.
0 commit comments