So I am learning on Data Structures and Algorithms currently working on Stacks, Queues and Dequeus
I have this question that says I should implement a Stack to check if the string given has balanced parenthesis and I am told in the question that the string contains only parenthesis and the string has no spaces
So I did implement my Stack class and then tried solving the problem Checking if the Parenthesis balance and I did a simple test case '[]' and it return False instead of True
So I fail to spot the error in the code.
Below is my thought process to solving the question so you can clearly see where I could have went wrong:
Firstly I checked if the length of the string is even if not I return
FalseI scan through the string and every time I see an opening parenthesis I push it to the stack
Then when I see a closing parenthesis I use the knowledge of stacks that LIFO I know that if now I am seeing a closing parenthesis the previous one should be the corresponding opening which was the last item pushed to stack so I then pop it off the stack and save it into a variable
I then make a check if they correspond and if they do not I return
FalseI then check if the stack is Empty then I know the is no corresponding opening parenthesis I return
FalseFinally if the loop finished without any return I check if stack is empty I return
Trueelse IFalse
Code Below
class Stack(object):
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == 0
def get_size(self):
return len(self.items)
def push(self, data):
self.items.append(data)
def peek(self):
return self.items[len(self)-1]
def remove_item(self):
self.items.pop()
stack = Stack()
def balance_check(s):
if len(s) % 3 == 0:
return False
openings = set('({[')
matches = set([ ('{', '}') , ('(', ')') , ('[', ']') ])
for paren in s:
if paren in openings:
stack.push(paren)
else:
if stack.get_size() == 0:
return False
last_open = stack.remove_item()
if (last_open, paren) not in matches:
return False
if stack.get_size() == 0:
return True
print(balance_check('[]'))