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 =
29
>> find_matching_paren(s, 6)
ans =
8
>> find_matching_paren(s, 27)
ans =
19
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
Problem Comments
-
3 Comments
Qianqian Fang
on 6 May 2019
wondering if there is a place I can review the submitted solution source codes? I think this is a great place to learn about matlab programming.
goc3
on 17 May 2019
@Qianqian Fang: once you've solved a problem, click on the solution map (containing all the green circles and orange x's). On that separate page you can click on each of the shapes to view each solution below the chart.
Nikolaos Nikolaou
on 30 Jul 2019
somehow i get that s='()' is there something wrong with the test suite?
Solution Comments
Show commentsProblem Recent Solvers292
Suggested Problems
-
331 Solvers
-
1391 Solvers
-
Count consecutive 0's in between values of 1
437 Solvers
-
7107 Solvers
-
Tick. Tock. Tick. Tock. Tick. Tock. Tick. Tock. Tick. Tock.
942 Solvers
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!