After watching a youtube tutorial on a bracket validation algorithm I understand everything besides this line of code.
stack[-1] == closeToOpen[c]:
Going through the loop until I hit a closing bracket c turns into ")"
So I'm guessing the code would statically be
Stack[-1] #"(" == closeToOpen[")"]:
Here is where I get confused because I don't see why stack[-1] which is "(" is equal to closeToOpen[")"]
.
Is it because closeToOpen[")"]
returns the value of ")" which is "("?
def bracketCheck(s):
stack = [] # Open up empty stack DS
closeToOpen = { # Create dictionary to map closing brackets to opening brackets
"}": "{",
")": "(",
"]": "["
}
for c in s: # Go through each character in string
if c in closeToOpen: # If the character is a closing bracket in our dictionary
# If stack is not empty and the last character in the stack is equal to the character in the closing dictionary
if stack and stack[-1] == closeToOpen[c]:
stack.pop() # Delete the last character in the stack
else:
return False
else:
stack.append(c) # Add character to the stack
return True if not stack else False
print(bracketCheck("[()]"))
CodePudding user response:
As you can see in the following snippet:
closeToOpen = { # Create dictionary to map closing brackets to opening brackets
"}": "{",
")": "(",
"]": "["
}
closeToOpen
is a dictionary that maps closing brackets to their corresponding opening ones.
This effectively means that closeToOpen[")"] == "("
and when you have a "(" at the end of your stack and see a closing bracket you check whether "(" == closeToOpen[")"]
. If it is true, you pop one element from your stack because you know that they match. If they don't match, this means that the bracket is not valid so you return False.
If you reach the end of the loop without returning False, you check if the stack is empty and return True if so. Otherwise you return False, because if there are any open brackets left in the stack, it means that they lack their closing counter parts.