-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValid Parenthesis_redo.py
88 lines (62 loc) · 2.4 KB
/
Valid Parenthesis_redo.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
"""
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
bracketDictionary = {"(":")", "[":"]", "{":"}"}
stringLength = len(s)
currentPosition = 0
stringArray = []
#check to see tha the first bracket is not a close bracket
if s[currentPosition] not in bracketDictionary:
return (False)
while currentPosition <= stringLength-1:
#while accumulating open brackets, store them in a list to compare later
if s[currentPosition] in bracketDictionary:
stringArray.append(s[currentPosition])
else:
#end bracket detected, now compare to see if it pairs with the last item in the list.
if s[currentPosition] != bracketDictionary[stringArray.pop()]:
#if it does not match, the sequence is invalid and the function can return false
return (False)
#move our current position down the string
currentPosition += 1
#if our list is empty, it means that all the pairs have correctly matched.
if (stringArray == []):
return (True)
answer = Solution()
testString = "(((())))"
print("Checking the following brackets: ", testString)
if answer.isValid(testString):
print("Correct formation")
else:
print("Incorrect formation")
testString = "({[]})"
print("Checking the following brackets: ", testString)
if answer.isValid(testString):
print("Correct formation")
else:
print("Incorrect formation")
testString = "({[])}"
print("Checking the following brackets: ", testString)
if answer.isValid(testString):
print("Correct formation")
else:
print("Incorrect formation")
testString = "]"
print("Checking the following brackets: ", testString)
if answer.isValid(testString):
print("Correct formation")
if not answer.isValid(testString):
print("Incorrect formation")
testString = "["
print("Checking the following brackets: ", testString)
if answer.isValid(testString):
print("Correct formation")
if not answer.isValid(testString):
print("Incorrect formation")