Given a string str consisting of parenthesis from [ “(” , “)” , “{” , “}” , “[” , “]” ].
If the String is perfectly balanced return 0 else return the index(starting from 1)at which the nesting is found to be wrong.
Examples:
Input : str = “{[()]}[]”
Output : 0Input : str = “[{]()}”
Output : 3Input : str = “}[{}]”
Output : 1
Input : str = “{([]){”
Output : 7
Approach:
- First we are creating the lst1 and lst2 that will have the opening and closing brackets respectively
- Now we will create another list lst that will work as a Stack means if any closing brackets will appear in the string then the respective opening brackets present in the lst will be deleted
- If any closing brackets will appear in the string and no repective opening brackets is present in the lst then this will be the bad index we will return it
- If we reach at the end of the string while traversing and the size of the lst is not equals to 0 we will return the len(String)+1
Note : We are using python dictionary to get the respective opening brackets for a closing one.
Below is the impementation of the above approach
# Write Python3 code here # Defining the string string = "{[()]}[]" # Storing opening braces in list lst1 lst1 = [ '{' , '(' , '[' ] # Storing closing braces in list lst2 lst2 = [ '}' , ')' , ']' ] # Creating an empty list lst lst = [] # Creating dictionary to map # closing braces to opening ones Dict = { ')' : '(' , '}' : '{' , ']' : '[' } a = b = c = 0 # If first position of string contain # any closing braces return 1 if string[ 0 ] in lst2: print ( 1 ) else : # If characters of string are opening # braces then append them in a list for i in range ( 0 , len (string)): if string[i] in lst1: lst.append(string[i]) k = i + 2 else : # When size of list is 0 and new closing # braces is encountered then print its # index starting from 1 if len (lst) = = 0 and (string[i] in lst2): print (i + 1 ) c = 1 break else : # As we encounter closing braces we map # them with theircorresponding opening # braces using dictionary and check # if it is same as last opened braces #(last element in list) if yes then we # delete that elememt from list if Dict [string[i]] = = lst[ len (lst) - 1 ]: lst.pop() else : # Otherwise we return the index # (starting from 1) at which # nesting is found wrong print (i + 1 ) a = 1 break # At end if the list is empty it # means the string is perfectly nested if len (lst) = = 0 and c = = 0 : print ( 0 ) b = 1 if a = = 0 and b = = 0 and c = = 0 : print (k) |
0
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.