Solution in C# using stack


  • 0
    D
    public class Solution {
        public bool IsValid(string s) {
            char[] arr = s.ToCharArray();
            if (arr[0] == ')' || arr[0] == ']' || arr[0] == '}') return false;
            if (s.Length % 2 == 1) return false;
            Stack myStack = new Stack();
            myStack.Push(arr[0]);
            char varChar;
            for (int i = 1;i<s.Length;i++)
                {
                    varChar = myStack.Count == 0?'0':(char)(myStack.Peek());    
                    if ((int)arr[i] - (int)varChar < 3 && (int)arr[i] - (int)varChar > 0 && myStack.Count != 0) myStack.Pop();
                    else if (myStack.Count == 0 || arr[i] == '(' || arr[i] == '[' || arr[i] == '{') myStack.Push(arr[i]);
                    else return false;
                }      
            if(myStack.Count != 0) return false;
            return true;
        }
    }
    

Log in to reply
 

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