C# solution


  • 0
    K
    public class Solution {
        public bool IsValid(string s) {
            if(s.Length%2 !=0)
                return false;
            Stack<char> st = new Stack<char>();
            Dictionary<char,char> dict = new Dictionary<char,char>();
            dict.Add('(',')');
            dict.Add('{','}');
            dict.Add('[',']');
            dict.Add(')','(');
            dict.Add('}','{');
            dict.Add(']','[');
            bool match = true;
            for(int i=0;i<s.Length;i++)
            {
                if(s[i] == '(' || s[i] == '[' || s[i] == '{')
                {
                    st.Push(s[i]);
                }
                else if (s[i] == ')' || s[i] == ']' ||s[i] == '}')
                {
                    char popped = '\0';
                    if(st.Count!=0)
                        popped = st.Pop();
                        
                    if(popped != dict[s[i]])
                     {
                         match = false;
                         break;
                     }
                }
            }
            if(st.Count > 0)
                match = false;
            
            return match;
        }
    }
    

Log in to reply
 

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