Best C# Solution


  • 0
    K
        public bool IsValid(string s)
        {
            Stack<char> stack = new Stack<char>();
            foreach(char c in s){
                if (c == '(' || c == '{' || c == '['){
                    stack.Push(c);
                }
                else{
                    if (stack.Count == 0)
                        return false;
                    char curr = stack.Peek();
                    if (c == ')' && curr != '(' || c == '}' && curr != '{' || c == ']' && curr != '[')
                        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.