Solution in Python


  • 0
    M
    class Solution:
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            count1=0;
            count2=0;
            count3=0;
            Ongoing=[];
            for char in s:
                if char=='(':
                    count1+=1;
                    Ongoing.append(0);
                elif char==')':
                    count1-=1
                    if count1<0: return False
                    if Ongoing[-1]!=0: return False
                    Ongoing=Ongoing[:-1]
                elif char=='[':
                    count2+=1
                    Ongoing.append(1)
                elif char==']':
                    count2-=1
                    if count2<0: return False
                    if Ongoing[-1]!=1: return False
                    Ongoing=Ongoing[:-1]
                elif char=='{':
                    count3+=1;
                    Ongoing.append(2)
                elif char=='}':
                    count3-=1
                    if count3<0: return False
                    if Ongoing[-1]!=2: return False
                    Ongoing=Ongoing[:-1]
            if count1+count2+count3>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.