Nice clean c# solution


  • 1
                Stack<char> stack = new Stack<char>();
                if (s.Length % 2 == 1) return false;
                for (int i = 0; i < s.Length; i++)
                {
                    if (s[i] == '(')
                    {
                        stack.Push(')');
                    }
                    else if (s[i] == '[')
                    {
                        stack.Push(']');
                    }
                    else if (s[i] == '{')
                    {
                        stack.Push('}');
                    }
                    else
                    {
                        if (stack.Count == 0 || s[i] != stack.Pop())
                        {
                            return false;
                        }
                    }
                }
                return (stack.Count == 0);
    

  • 0
    K

    Really nice solution!! Just tweaked to avoid conditionals

    Stack<char> stack = new Stack<char>();
                if ((s.Length & 1) == 1) return false;
                Dictionary<char, char> d = new Dictionary<char, char>();
                d.Add('(', ')');
                d.Add('{', '}');
                d.Add('[', ']');
                for (int i = 0; i < s.Length; i++)
                {
                   if (d.ContainsKey(s[i])) 
                       stack.Push(d[s[i]]);
                    else
                    {
                        if (stack.Count == 0 || s[i] != 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.