Solution in C#


  • 0
    P
            public bool isValid(string s)
            {
                Dictionary<char, char> parenthesisPair = new Dictionary<char, char>();
                parenthesisPair.Add('}', '{');
                parenthesisPair.Add(')', '(');
                parenthesisPair.Add(']', '[');
    
                Stack<char> inStr = new Stack<char>();
    
                for (int i = 0; i < s.Length; i++)
                {
                    if (parenthesisPair.ContainsKey(s[i]))
                    {
                        if (inStr.Count > 0)
                        {
                            if (inStr.Pop() != parenthesisPair[s[i]])
                            {
                                return false;
                            }
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else if (parenthesisPair.ContainsValue(s[i]))
                    {
                        inStr.Push(s[i]);
                    }
                }
    
                return (inStr.Count == 0);
            }
    

Log in to reply
 

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