C#, 108ms, accepted solution


  • 0
    D
    
    public class Solution {
        public bool IsValid(string s) {
            int n = s.Length; 
            if(n%2!=0) return false;
            char[] c = s.ToCharArray();
            Dictionary<char,char> LeftParenthesis = new Dictionary<char,char>();
            LeftParenthesis['('] = ')';
            LeftParenthesis['['] = ']';
            LeftParenthesis['{'] = '}';
            Dictionary<char,char> RightParenthesis = new Dictionary<char,char>();
            RightParenthesis[')'] = '(';
            RightParenthesis['}'] = '{';
            RightParenthesis[']'] = '[';
            
           Stack<char> stack = new Stack<char>();
    
            for(int i=0; i<n ;i++)
            {
                if(LeftParenthesis.ContainsKey(c[i])){
                    stack.Push(c[i]);
                }
                else if(RightParenthesis.ContainsKey(c[i])){
                    if(stack.Count==0) return false;
                    char stackelement = stack.Pop();
                    if( LeftParenthesis[stackelement] !=c[i]) return false;
                }
                /* variation - if no other characters are allowed;
                else{
                    return false;
                }
                */
            }
            if(stack.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.