Given a string of length N, output “Correct” if brackets close in correct order else output “Incorrect”

Question:

Given a string of length N, output “Correct” if brackets close in correct order else output “Incorrect”

Input     :   ({}[((({{}})[{()}]))])

Solution(Python):

    # Author            :        Sreejith Sreekantan
    # Description        :        

    #                         Given a string of length N, output "Correct" if brackets close in correct order else output "Incorrect"
    #                         Input     : ({}[((({{}})[{()}]))])
    #                         

#!/usr/bin/python
def validString(input1):
    stk = []
    flag = True
    for x in input1:
        if x in ['{', '(', '[']:
            stk.append(x)
        else:
            if  len(stk)==0:
                flag = False
            elif x == '}' and not stk[len(stk)-1]=='{' :
                flag = False    
            elif x == ')' and not stk[len(stk)-1]=='(' :
                flag = False 
            elif x == '}' and not stk[len(stk)-1]=='{' :
                flag = False    
            if not flag:
                return "Incorrect"
            else:
                stk.pop()
    return "Correct"
 

input1 = '({}[((({{}})[{()}]))])'
input2 = '({}((({{}})[{()}]))])'
print validString(input1)    
print validString(input2)

Published by

Sreejith

A strong believer of: 1. Knowledge is power 2. Progress comes from proper application of knowledge 3. Reverent attains wisdom 4. For one's own salvation, and for the welfare of the world

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s