DEV Community

Discussion on: Parenthetically Speaking

Collapse
 
r0f1 profile image
Florian Rohrer

I like this, because this is one of the classical problems that you learn in introduction to formal methods of computer science. In order to determine, if a string is well-balanced, you need a grammar that is at least context-free. A regular grammar, does not suffice.

Implementing a context-free grammar, can be done using a stack. So you can also solve this problem using a stack. Whenever you encounter a (, push it onto the stack. Whenever you encounter a ), pop a ( from the stack. If there is no ( on the stack when you try to pop one, return false. If the stack is not empty when you are done processing the string, return false. Otherwise, the string is well-balanced.