Checking string has balanced parentheses

后端 未结 18 2354
谎友^
谎友^ 2020-12-01 08:42

I am reading the Algorithm Design Manual Second Edition and this is from an exercise question. Quoting the question

A common problem for comp

18条回答
  •  眼角桃花
    2020-12-01 08:48

    Piggy back on @Russell's idea:

    public class BalancedBrackets
    {
        private readonly char[] _leftBrackets = new char[] {'[', '(', '{', '<'};
        private readonly char[] _rightBrackets = new char[] {']', ')', '}', '>'};
    
        public bool IsBalanced(string input)
        {
            int count = 0;
            foreach (var character in input.ToCharArray())
            {
                if (_leftBrackets.Contains(character)) count++;
                if (_rightBrackets.Contains(character)) count--;
            }
            return count == 0;
        }
    }
    

提交回复
热议问题