Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Check for Balanced Parenthesis in a String

4.43/5 (6 votes)
9 Mar 2017CPOL 53.9K  
Solution to check for balanced parentheses in a string where parentheses are defined as (, [ or { and their respective closing parentheses.

Introduction

Checks a string for balanced parenthesis, i.e., whether all opening or left hand parenthesis have a closing or right hand parenthesis and are those logically placed in a string. Can be used to validate a numerical formula or a LINQ expression, or to check if an xml/json is well-formed, etc.

Background

Using Stack to solve this problem.

Using the Code

Use Stack, while iterating through each character of the input string, to Push any opening brackets to the stack and to Pop the closing bracket if it matches the closing bracket of the latest opening bracket in the stack. At the end of the iteration, if the stack is empty, then all the brackets were balanced.

C#
public static bool IsBalanced(string input)
    {
        Dictionary<char, char> bracketPairs = new Dictionary<char, char>() {
            { '(', ')' },
            { '{', '}' },
            { '[', ']' },
            { '<', '>' }
        };

        Stack<char> brackets = new Stack<char>();

        try
        {
            // Iterate through each character in the input string
            foreach (char c in input)
            {
                // check if the character is one of the 'opening' brackets
                if (bracketPairs.Keys.Contains(c))
                {
                    // if yes, push to stack
                    brackets.Push(c);
                }
                else
                // check if the character is one of the 'closing' brackets
                    if (bracketPairs.Values.Contains(c))
                {
                    // check if the closing bracket matches the 'latest' 'opening' bracket
                    if (c == bracketPairs[brackets.First()])
                    {
                        brackets.Pop();
                    }
                    else
                        // if not, its an unbalanced string
                        return false;
                }
                else
                    // continue looking
                    continue;
            }
        }
        catch
        {
            // an exception will be caught in case a closing bracket is found, 
            // before any opening bracket.
            // that implies, the string is not balanced. Return false
            return false;
        }

        // Ensure all brackets are closed
        return brackets.Count() == 0 ? true : false;
    }

Examples

  1. Input: "[288 votes so far. Categories: {"Everything Else" (47 votes), C# (61 votes), C++ (39 votes), Database (44 votes), Mobile (45 votes), Web Dev (52 votes)}]"

    Output: true

  2. Input: "[{}()<sometext>[[{{}}]]]"

    Output: true

  3. Input: "<Root><First>Test</First<</Root>"

    Output: false

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)