Parenthesis/Brackets Matching using Stack algorithm

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

    I have seen answers here and almost all did well. However, I have written my own version that utilizes a Dictionary for managing the bracket pairs and a stack to monitor the order of detected braces. I have also written a blog post for this.

    Here is my class

    public class FormulaValidator
    {
        // Question: Check if a string is balanced. Every opening bracket is matched by a closing bracket in a correct position.
        // { [ ( } ] )
    
        // Example: "()" is balanced
        // Example: "{ ]" is not balanced.
        // Examples: "()[]{}" is balanced.
        // "{([])}" is balanced
        // "{ ( [ ) ] }" is _not_ balanced
    
        // Input: string, containing the bracket symbols only
        // Output: true or false
        public bool IsBalanced(string input)
        {
            var brackets = BuildBracketMap();
            var openingBraces = new Stack();
            var inputCharacters = input.ToCharArray();
    
            foreach (char character in inputCharacters)
            {
                if (brackets.ContainsKey(character))
                {
                    openingBraces.Push(character);
                }
    
                if (brackets.ContainsValue(character))
                {
                    var closingBracket = character;
                    var openingBracket = brackets.FirstOrDefault(x => x.Value == closingBracket).Key;
    
                    if (openingBraces.Peek() == openingBracket)
                        openingBraces.Pop();
                    else
                        return false;
                }
            }
    
            return openingBraces.Count == 0;
        }
    
        private Dictionary BuildBracketMap()
        {
            return new Dictionary()
            {
                {'[', ']'},
                {'(', ')'},
                {'{', '}'}
            };
        }
    }
    

提交回复
热议问题