Problem 111. Find matching parenthesis

One of the most indispensable things about a great text editor for programming is the ability to quickly jump between matching parentheses. If you have a line like,

    if (f(a) >= b(c, d(e*(f-g))))

it very convenient to place your cursor at, say, the second to last closing parenthesis, and have the editor show you where is the matching opening parenthesis. (In this example, it is the one just after b.)

For this problem, you should write a function that takes a string s like 'if (f(a) >= b(c, d(e*f(-g))))' and an integer n representing a character position within the string. Your function should return the index of the matching parenthesis.

For example:

    >> s = 'if (f(a) >= b(c, d(e*f(-g))))';
    >> find_matching_paren(s, 4)
    ans =
    >> find_matching_paren(s, 6)
    ans =
    >> find_matching_paren(s, 27)
    ans =

You can assume that n will always be the position of either an open or closing parenthesis.

You can assume the string will always have balanced parentheses.

Solution Stats

54.85% Correct | 45.15% Incorrect
Last solution submitted on Jul 26, 2017

Problem Comments

Solution Comments

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!