Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are many ways to do this, but the simplest algorithm is to simply process forward left to right, passing the stack as a parameter</p> <pre><code>FUNCTION isBalanced(String input, String stack) : boolean IF isEmpty(input) RETURN isEmpty(stack) ELSE IF isOpen(firstChar(input)) RETURN isBalanced(allButFirst(input), stack + firstChar(input)) ELSE IF isClose(firstChar(input)) RETURN NOT isEmpty(stack) AND isMatching(firstChar(input), lastChar(stack)) AND isBalanced(allButFirst(input), allButLast(stack)) ELSE ERROR "Invalid character" </code></pre> <hr> <p>Here it is implemented in Java. Note that I've switched it now so that the stack pushes in <em>front</em> instead of at the <em>back</em> of the string, for convenience. I've also modified it so that it just skips non-parenthesis symbols instead of reporting it as an error.</p> <pre><code>static String open = "([&lt;{"; static String close = ")]&gt;}"; static boolean isOpen(char ch) { return open.indexOf(ch) != -1; } static boolean isClose(char ch) { return close.indexOf(ch) != -1; } static boolean isMatching(char chOpen, char chClose) { return open.indexOf(chOpen) == close.indexOf(chClose); } static boolean isBalanced(String input, String stack) { return input.isEmpty() ? stack.isEmpty() : isOpen(input.charAt(0)) ? isBalanced(input.substring(1), input.charAt(0) + stack) : isClose(input.charAt(0)) ? !stack.isEmpty() &amp;&amp; isMatching(stack.charAt(0), input.charAt(0)) &amp;&amp; isBalanced(input.substring(1), stack.substring(1)) : isBalanced(input.substring(1), stack); } </code></pre> <p>Test harness:</p> <pre><code> String[] tests = { "()[]&lt;&gt;{}", "(&lt;", "]}", "()&lt;", "(][)", "{(X)[XY]}", }; for (String s : tests) { System.out.println(s + " = " + isBalanced(s, "")); } </code></pre> <p>Output:</p> <pre><code>()[]&lt;&gt;{} = true (&lt; = false ]} = false ()&lt; = false (][) = false {(X)[XY]} = true </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload