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.
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.
@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.
somehow i get that s='()' is there something wrong with the test suite?
第一次解决问题时，想了很长时间....然并卵
第二次看这个问题，十分钟内解决
It is curious that many solutions checks the "direction" of given parenthesis to find it's pair.
wow I don't find the words to comment this solution except who can read that?!!
Wonderful solution.
Technically, I don't understand where ans is created. If I break this code, I obtain an error (ans is undefined). It seems that the line 4 create ans but only in the function (?).
Hi Jean-Marie. I haven't bee around for some time now. Well, that turned out to be a bug...
http://www.mathworks.com/matlabcentral/answers/46972-is-this-a-possible-matlab-bug-further-strange-behavior
Brilliant !!!
vectors, schmectors!
How to find the position of an element in a vector without using the find function
2357 Solvers
given 3 sides, find area of this triangle
608 Solvers
Similar Triangles - find the height of the tree
161 Solvers
291 Solvers
105 Solvers