Version 2 of Balanced Brackets

Updated 2018-07-22 14:22:33 by pooryorick

Created by CecilWesterhof.

During in an interview I got a question about how to implement checking if a string containing brackets was valid.

For example the following are valid:

"{()}"
"{\[()]}"
"{{\[\[(())]]}}"

And the following is invalid:

"{\[(])}"

I implemented that in Java, but found it interesting to try it in Tcl. It saves some work.

I kept it relatively simple. For example if the stack contains more elements as the rest of the string contains, you know the complete string is not valid. (I implemented this in the Java version, but thought it made the code a little harder to read, without a significant gain.)

The implementation:

proc balancedBrackets {string} {
    if {[expr {[string length $string] % 2}]} {
        return 0
    }
    set stack {}

    foreach ch [split ${string} {}] {
        switch -- ${ch} {
            \( {
                lappend stack \)
            }
            \[ {
                lappend stack \]
            }
            \{ {
                lappend stack \}
            }
            \) -
            \] -
            \} {
                if {[lindex ${stack} end] ne ${ch}} {
                    return 0
                }
                set stack [lrange ${stack} 0 end-1]
            }
            default {
                error "Wrong character: ${ch}"
            }
        }
    }
    return [expr {[llength ${stack}] == 0}]
}

The following code:

puts [balancedBrackets "{()}"]
puts [balancedBrackets "{\[()]}"]
puts [balancedBrackets "{{\[\[(())]]}}"]
puts [balancedBrackets "{\[(])}"]

gives:

1
1
1
0

In the near future I am going to implement some improvements. I like the brackets to be a parameter. For example it could be extended with < and >, but only if you want it.


As always: comments, tips and questions are appreciated.

PYK 2018-07-22: What is the definition of "valid string" for this exercise?