Iterative O(N) solution in C#


  • 0
    R
        public bool IsValid(string s) {
            Stack<char> stack = new Stack<char>();
            
            foreach(var ch in s)
            {
                if(ch == '(' || ch == '[' || ch == '{') stack.Push(ch);
                
                if((ch == ')' && !(stack.Count > 0 && stack.Pop() == '(')) || 
                   (ch == ']' && !(stack.Count > 0 && stack.Pop() == '[')) ||
                   (ch == '}' && !(stack.Count > 0 && stack.Pop() == '{'))) 
                {
                    return false;
                }
            }
            
            return !(stack.Count > 0);
        }
    

Log in to reply
 

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