C# Classic Version with Dictionary


  • 0
    L
    public class Solution {
        public bool IsValid(string s) {
            Dictionary<char, char> dc = new Dictionary<char, char>();
            dc.Add(')', '(');
            dc.Add(']', '[');
            dc.Add('}', '{');
    
            int i = 0;
            Stack<char> stack = new Stack<char>();
            while (i < s.Length)
            {
                if (dc.ContainsKey(s[i]))
                {
                    if (stack.Count == 0) return false;
                    if (dc[s[i]] != stack.Pop())
                        return false;
                }
                else
                    stack.Push(s[i]);
    
                i++;
            }
            if (stack.Count == 0)
                return true;
            else
                return false;
        }
    }

Log in to reply
 

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