Solution in C# with on stack


  • 0
    H
    public class Solution {
        public bool IsValid(string s) {
            bool result = false;
            Stack<string> stack = new Stack<string>();
            Dictionary<string, string> parentheses = new Dictionary<string, string> { { "{", "}" }, { "[", "]" }, { "(", ")" } };
            for (int i = 0; i < s.Length; i++)
            {
                // Continue if the parentheses is not in the above dictionary
                if (!(parentheses.ContainsKey(s[i].ToString()) || parentheses.ContainsValue(s[i].ToString())))
                    continue;
                
                // Look for the open brackst
                if (parentheses.ContainsKey(s[i].ToString()))
                    stack.Push(s[i].ToString());
                    
                // Look for the closing bracket
                else if (stack.Count > 0)
                {
                    // stack count should be >0 and pop value should contains in th dictionary
                    string lastBracket = stack.Pop();
                    if (parentheses.ContainsKey(lastBracket) && parentheses[lastBracket].Equals(s[i].ToString()))
                        continue;
                    else if (parentheses.ContainsKey(lastBracket) && !parentheses[lastBracket].Equals(s[i].ToString()))
                        return result;
                }
                else if (parentheses.ContainsValue(s[i].ToString()))
                    stack.Push(s[i].ToString());
            }
            if (stack.Count == 0)
                return true;
            return result;
    }
    

    }


Log in to reply
 

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