Click here to Skip to main content
15,884,629 members
Articles / Programming Languages / C#
Tip/Trick

Check for Balanced Parenthesis in a String

Rate me:
Please Sign up or sign in to vote.
4.43/5 (6 votes)
9 Mar 2017CPOL 52.6K   4   10
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)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralQuoted text? Pin
PIEBALDconsult11-Mar-17 4:53
mvePIEBALDconsult11-Mar-17 4:53 
Questionpffffff, Pin
mag1311-Mar-17 3:46
mag1311-Mar-17 3:46 
tehnical leader, ..... (i kill my self) .... hey just learn to use RegEx, must fast and must eficient code.
magsoft

AnswerMessage Closed Pin
11-Mar-17 4:34
TarunSingla11-Mar-17 4:34 
GeneralRe: pffffff, Pin
mag1311-Mar-17 5:07
mag1311-Mar-17 5:07 
GeneralRe: pffffff, Pin
mag1311-Mar-17 5:22
mag1311-Mar-17 5:22 
PraiseNice, but ... Pin
RickZeeland10-Mar-17 3:33
mveRickZeeland10-Mar-17 3:33 
GeneralRe: Nice, but ... Pin
chrono_dev10-Mar-17 5:39
chrono_dev10-Mar-17 5:39 
GeneralRe: Nice, but ... Pin
RickZeeland10-Mar-17 6:47
mveRickZeeland10-Mar-17 6:47 
SuggestionNice Pin
Robert Vandenberg Huang10-Mar-17 1:50
professionalRobert Vandenberg Huang10-Mar-17 1:50 
SuggestionA nice piece of code. Pin
Rul Aman9-Mar-17 22:23
Rul Aman9-Mar-17 22:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.