A Different C# Solution Using Stack & Dictionary


  • 0
    M
    public bool IsValid(string s)
    {
        Dictionary<char, int> dict = new Dictionary<char, int>();
        dict.Add('(', 10); dict.Add(')', 11);
        dict.Add('[', 20); dict.Add(']', 21);
        dict.Add('{', 30); dict.Add('}', 31);
        Stack<char> stack = new Stack<char>();
        for(int i = 0; i < s.Length; i++)
        {
            //Right Parentheses
            if(dict[s[i]] % 10 != 0)  
            {
                //No Pair
                if(stack.Count == 0) return false;
                //Wrong Pair
                else if(dict[s[i]] -  dict[stack.Pop()] != 1) return false;
            }
            //Left Parentheses
            else stack.Push(s[i]);
        }
        return stack.Count == 0;
    }
    

    Store 6 different symbols into the dictionary beforehand, left parentheses has value % 10 == 0, and each pair of parentheses has value difference of 1.


Log in to reply
 

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