Parenthesis/Brackets Matching using Stack algorithm

前端 未结 30 2732
你的背包
你的背包 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:23

    public static bool IsBalanced(string input)
        {
            Dictionary bracketPairs = new Dictionary() {
            { '(', ')' },
            { '{', '}' },
            { '[', ']' },
            { '<', '>' }
        };
    
            Stack brackets = new Stack();
    
            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;
        }
    

提交回复
热议问题