C# O(n) Accepted Solution with switch


  • 0
    S

    Using stack to store parentheses, if it's the left parentheses, store into stack directly, if it's the right parentheses, judge if the top parenthese of stack matches. Match-->pop the top parenthese; doesn't match--> push the right parenthese into stack. if the stack count is 0 at the end, then the string is valid.

    
    public class Solution {
        public bool IsValid(string s) {
            if(s==null || s.Length==0) return true;
            
            if(s.Length%2==1) return false; //the string length is odd, then return false
            
            //when string length is even, use stack to store parentheses.
            //all the left parentheses will directly be stored in stack.
            //If the right half comes, check the top of stack, if the top parenthese matches, then pop the top parenthese
            //Otherwise, push the parenthese to stack
            // if at the end, if the stack is empty is 0, then all parentheses are valid.
            Stack<char> k = new Stack<char>();
            
           for(int i=0; i<s.Length; i++)
           {
               switch(s[i])
               {
                   case '(': k.Push(s[i]);
                            break;
                   case '{': k.Push(s[i]);
                            break;
                   case '[': k.Push(s[i]);
                            break;
                   case ')': 
                   {
                        if(k.Count>0 && k.Peek()=='(') k.Pop();
                        else k.Push(s[i]);
                        break;
                   }
                   case '}': 
                   {
                        if(k.Count>0 && k.Peek()=='{') k.Pop();
                        else k.Push(s[i]);
                        break;
                   }
                   case ']': 
                   {
                        if(k.Count>0 && k.Peek()=='[') k.Pop();
                        else k.Push(s[i]);
                        break;
                   }     
               }
           }
            
            k.TrimExcess();
            if(k.Count==0) return true;
            
            return false;
        }
    }
    
    
    
    

Log in to reply
 

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