A C# solution


  • 0
    S

    My C# solution

    using System.Collections.Generic;
    
    public class Solution {
        public bool IsValid(string s) {
            if (string.IsNullOrWhiteSpace(s))
            {
                return false;
            }
    
            Stack<char> stack = new Stack<char>();
            foreach(var c in s)
            {
                if (c == '(' || c == '{' || c == '[')
                {
                    stack.Push(c);
                    continue;
                }
    
                if (stack.Count == 0)
                {
                    return false;
                }
                var top = stack.Peek();
                if ((c == ')' && top != '(') || (c =='}' && top != '{') || (c == ']' && top != '['))
                {
                    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.