Hello
Can you assist me in developing my algorithm?
I have to do this:
Write a C++ function balanced that uses a stack to check that all brackets in a string are balanced.
For eg:
This is a balance string:
This (string) has (balanced {brackets[(now)]} [thanks])This string is not balanced:
This [[string has (bad} brackets]>)
I am strugling thinking of a way of doing this using stacks.
My idea so far is:
Check each character of a string:
- if the character is any of these "[{(<" then (open.push(1)) - where open is a stack of integers.
- else if the character is any of these "]})>" then (close.push(1)) - where close is a stack of integers.
- else do nothing
If we reach the end of the string & open.size() == close.size() then the string is balanced
, if not then the string is not balanced.
This is the only way I can think of, although it does not really utilise the features of a stack, because I could just use int counters to replace the stacks open & close & it would still work.(i am just counting open & closed brackets).
Any ideas how I could use stacks (LIFO characteristics) to find if a string is balanced? :)