Pop each element. Check if there are equal matching braces/brackets...
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
Well, do you have to do anything with these strings of characters or are you just making sure everything's balanced?
If the latter, there's not a lot to it. First, ignore anything that isn't a bracket of some sort. You push any opening bracket you run into. When you hit a closing bracket, you pop. One, there had better be something to pop. Two, what is popped had better be the corresponding opening bracket to the closing bracket you just encountered. Three, at the end, you'd better have an empty stack.
If any of these three criteria fail at any point, it's unbalanced. If all tests pass, it's balanced.
This [[string has (bad} brackets]>)
Ignore all non-brackets:
[[(}]>)
Go left to right.[ is an opening bracket. Push it.
[ is an opening bracket. Push it.
( is an opening bracket. Push it.
} is a closing bracket. Pop.
Your pop is (, which doesn't match }. Test 2 fails. The string is therefore not balanced.
VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711