Basic Recursion, Check Balanced Parenthesis

前端 未结 12 1209
孤独总比滥情好
孤独总比滥情好 2020-11-29 17:56

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 neste

12条回答
  •  遥遥无期
    2020-11-29 18:12

    It doesn't really matter from a logical point of view -- if you keep a stack of all currently un-balanced parens that you pass to each step of the recursion, you'll never need to look backwards, so it doesn't matter if you cut up the string on each recursive call, or just increment an index and only look at the current first character.

    In most programming languages, which have non-mutable strings, it's probably more expensive (performance-wise) to shorten the string than it is to pass a slightly larger string on the stack. On the other hand, in a language like C, you could just increment a pointer within the char array. I guess it's pretty language-dependent which of these two approaches is more 'efficient'. They're both equivalent from a conceptual point of view.

提交回复
热议问题