Monday, August 22, 2016

Leetcode 20. Valid Parentheses

 public class Solution {  
   public bool IsValid(string s) {  
     if (s == null)  
     {  
       return false;  
     }  
     char[] a = s.ToCharArray();  
     List<char> stack = new List<char>();  
     foreach(char c in a)  
     {  
       if (c =='(' || c=='[' || c=='{')  
       {  
         stack.Add(c);  
       }  
       else  
       {  
         if (c==')')  
         {  
           if (stack.Count ==0 || stack[stack.Count - 1] != '(')  
           {  
             return false;  
           }  
           stack.RemoveAt(stack.Count - 1);  
         }  
         if (c==']')  
         {  
           if (stack.Count ==0 || stack[stack.Count - 1] != '[')  
           {  
             return false;  
           }  
           stack.RemoveAt(stack.Count - 1);  
         }  
         if (c=='}')  
         {  
           if (stack.Count ==0 || stack[stack.Count - 1] != '{')  
           {  
             return false;  
           }  
           stack.RemoveAt(stack.Count - 1);  
         }  
       }  
     }  
     if (stack.Count != 0)  
     {  
       return false;  
     }  
     return true;  
   }  
 }  

No comments:

Post a Comment