I've written software in the past that uses a stack to check for balanced equations, but now I'm asked to write a similar algorithm recursively to check for properly nested brackets and parenthesis.
Good examples: () [] () ([]()[])
Bad examples: ( (] ([)]
Suppose my function is called: isBalanced.
Should each pass evaluate a smaller substring (until reaching a base case of 2 left)? Or, should I always evaluate the full string and move indices inward?
It should be a simple use of stack ..
The idea is to keep a list of the opened brackets, and if you find a closing brackt, check if it closes the last opened:
When the string is finally empty, if the list of brackes is empty too (so all the brackes has been closed) return
true
, elsefalse
ALGORITHM (in Java):
TEST:
OUTPUT:
Note that i have imported the following classes:
PHP Solution to check balanced parentheses
First, to your original question, just be aware that if you're working with very long strings, you don't want to be making exact copies minus a single letter each time you make a function call. So you should favor using indexes or verify that your language of choice isn't making copies behind the scenes.
Second, I have an issue with all the answers here that are using a stack data structure. I think the point of your assignment is for you to understand that with recursion your function calls create a stack. You don't need to use a stack data structure to hold your parentheses because each recursive call is a new entry on an implicit stack.
I'll demonstrate with a C program that matches
(
and)
. Adding the other types like[
and]
is an exercise for the reader. All I maintain in the function is my position in the string (passed as a pointer) because the recursion is my stack.Tested with this code:
Output:
Balanced Parenthesis (JS)
The more intuitive solution is to use stack like so:
And using recursive function (without using stack), might look something like so:
* As @Adrian mention, you can also use stack in the recursive function without the need of looking backwards