C# Code - Runtime: 88ms - Beating 94.54%


  • 0
    A
      public class Solution
        {
            public bool IsValid(string s)
            {
                bool valid = true;
    
                Stack k = new Stack();
                char[] c = s.ToCharArray();
    
                for (int i = 0; i < s.Length; i++)
                {
                    if (c[i] == '(' || c[i] == '{' || c[i] == '[')
                    {
                        k.Push(c[i]);
                    }
                    else
                    {
                        if(k.Count ==0)
                        {
                            valid = false; break;
                        }
                        else
                        {
                            if (k.Peek() is null)
                            {
                                valid = false; break;
                            }
                            else
                            {
                                char l = char.Parse(k.Pop().ToString());
                                if ((GetC(l) == 'o' || GetC(l) != c[i]))
                                {
                                    valid = false; break;
                                }
                            }
                        }
                        
                    }
                }
                if (k.Count != 0) valid = false;
                return valid;
            }
    
            public char GetC(char l)
            {
                if (l == '[')
                    return ']';
                if (l == '(')
                    return ')';
                if (l == '{')
                    return '}';
                else
                    return 'o';
            }
        }
    

Log in to reply
 

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