Parenthesis/Brackets Matching using Stack algorithm

前端 未结 30 2701
你的背包
你的背包 2020-11-27 11:39

For example if the parenthesis/brackets is matching in the following:

({})
(()){}()
()

and so on but if the parenthesis/brackets is not mat

30条回答
  •  遥遥无期
    2020-11-27 12:08

    Problem Statement: Check for balanced parentheses in an expression Or Match for Open Closing Brackets

    If you appeared for coding interview round then you might have encountered this problem before. This is a pretty common question and can be solved by using Stack Data Structure Solution in C#

            public void OpenClosingBracketsMatch()
            {
                string pattern = "{[(((((}}])";
                Dictionary matchLookup = new Dictionary();
                matchLookup['{'] = '}';
                matchLookup['('] = ')';
                matchLookup['['] = ']';
                Stack stck = new Stack();
                for (int i = 0; i < pattern.Length; i++)
                {
                    char currentChar = pattern[i];
                    if (matchLookup.ContainsKey(currentChar))
                        stck.Push(currentChar);
                    else if (currentChar == '}' || currentChar == ')' || currentChar == ']')
                    {
                        char topCharFromStack = stck.Peek();
                        if (matchLookup[topCharFromStack] != currentChar)
                        {
                            Console.WriteLine("NOT Matched");
                            return;
                        }
                    }
                }
    
                Console.WriteLine("Matched");
            }
    

    For more information, you may also refer to this link: https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/

提交回复
热议问题