A lot of text editors and IDEs have a feature that highlights matching parentheses, square brackets, or curly braces when the cursor is placed over either the opening or closing character in one of these pairs.
What algorithm is used to find the position of the matching parenthesis, given the position of either an opening or closing parenthesis in a text file? Keep in mind that these characters can be nested, so simply scanning forward or backward through the text until you find the opposite character is insufficient.
Example:
I recently ran into this problem when writing a brainf*ck interpreter in Java. [
and ]
in that language are analogous to a while loop, and can be nested. The interpreter needs to find the matching [
or ]
depending on the value at the data pointer. See the ROT13 example code for an illustration of nesting.
Push an opening parenthesis on top of the stack. In case of a closing bracket, check if the stack is empty. If not, pop in a closing parenthesis if the top of the stack contains the corresponding opening parenthesis. If the parentheses are valid, then the stack will be empty once the input string finishes.
Starting with an empty stack, process the parenthesis strings from left to right. If a symbol is an opening parenthesis, push it on the stack as a signal that a corresponding closing symbol needs to appear later. If, on the other hand, a symbol is a closing parenthesis, pop the stack.
Lesson Summary. Parentheses, brackets, and braces are ways of separating parts of a mathematical expression from one another, and they all look quite similar. Parentheses are smooth and curved ( ), brackets are square [ ], and braces are curly { }. In mathematics, they are mostly used for order of operations.
Given the position of an open parenthesis in an array of characters, there's a simple algorithm that uses a counter to find the matching close parenthesis.
In code this looks something like:
public int findClosingParen(char[] text, int openPos) { int closePos = openPos; int counter = 1; while (counter > 0) { char c = text[++closePos]; if (c == '(') { counter++; } else if (c == ')') { counter--; } } return closePos; }
The algorithm for finding the position of the matching open parenthesis given a closing parenthesis is the opposite.
In code:
public int findOpenParen(char[] text, int closePos) { int openPos = closePos; int counter = 1; while (counter > 0) { char c = text[--openPos]; if (c == '(') { counter--; } else if (c == ')') { counter++; } } return openPos; }
Note: Both of the examples above assume that parentheses are balanced, so no array bounds checking is done. A real implementation would check that you don't run off the end of the array, and throw an exception (or return an error code) that indicates that parentheses are unbalanced in the input text if you do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With