C# Accepted solution using stack


  • 0
    J
    public bool IsValid(string s) 
        {
            Stack<char> stack = new Stack<char>();
            if (s.Length == 0) return true;
            if (s.Length == 1) return false;
            
            foreach (var character in s)
            {
                if (character == '(' || character == '{' || character == '[')
                {
                    stack.Push(character);
                }
                else if (character == ')')
                {
                    if (stack.Count == 0 || stack.Peek() != '(') return false;
                    stack.Pop();
                }
                else if (character == '}')
                {
                    if (stack.Count == 0 || stack.Peek() != '{') return false;
                    stack.Pop();
                }
                else if (character == ']')
                {
                    if (stack.Count == 0 || stack.Peek() != '[') return false;
                    stack.Pop();
                }
            }
            return stack.Count == 0;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.