-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path6. ValidParentheses.py
50 lines (40 loc) · 1.19 KB
/
6. ValidParentheses.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#Problem Statement available at: https://leetcode.com/problems/valid-parentheses/
#Approach 1: optimised
class Solution:
def isValid(self, s: str) -> bool:
dic = {']':'[',')':'(','}':'{'}
stack = []
for ele in s:
if ele in dic:
if(stack != [] and dic[ele]==stack[-1]):
stack.pop()
else:
stack.append(ele)
else:
stack.append(ele)
if(stack == []):
return True
else:
return False
'''
#Approach 2
class Solution:
def isValid(self, s: str) -> bool:
dic = {'[':']','{':'}','(':')',']':'[',')':'(','}':'{'}
stack = []
size = len(s)
if ( s == ''):
return True
stack.append((s[0]))
for i in range(1,size):
if(stack == []):
stack.append(s[i])
elif(dic[stack[-1]] == s[i] ):
stack.pop()
else:
stack.append(s[i])
if(len(stack) ==0):
return True
else:
return False
'''