• + 1 comment

    @benedict_ I think if string is "))" or any string starts with closing brackets your code will fail.

    try this,it might help you

    #include <math.h>
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <assert.h>
    #include <limits.h>
    #include <stdbool.h>
    
    struct Stack
    {
        int data;
        struct Stack *next;
    };
    
    typedef struct Stack s;
    s *top=NULL,*neu;
    
    void push(int data)
    {
        neu = (s *)malloc(sizeof(s));
        neu->data = data;
        neu->next = NULL;
        
        if(!top)
        {
            top = neu;
        }
        else
        {
            neu->next = top;
            top = neu;
        }
    }
    
    void pop()
    {
        s *temp = top;
        top = top->next;
        free(temp);
    }
    
    
    char* isBalanced(char* s) {
        // Complete this function
        int i,len,flag=1;
        
        len = strlen(s);
        for(i=0;i<len;i++)
        {
            if((s[i]==')' || s[i]=='}' || s[i]==']') && (!top))
            {
                push(7);
                break;
            }
            else
            {
                if(s[i]=='(')
                {
                    push(1);
                }
                if(s[i]=='{')
                {
                    push(2);
                }
                if(s[i]=='[')
                {
                    push(3);
                }
                if(s[i]==')' && top->data==1)
                {
                    pop();
                }
                if(s[i]=='}' && top->data==2)
                {
                    pop();
                }
                if(s[i]==']' && top->data==3)
                {
                    pop();
                }
            }    
            
        }
        if(top )
        {
            while(top)
            {
                struct Stack *temp;
                temp = top;
                top = top->next;
                free(temp);
            }
            return "NO";
        }
        else
        {
            return "YES";
        }
    }
    
    int main() {
        int t; 
        scanf("%i", &t);
        for(int a0 = 0; a0 < t; a0++){
            char* s = (char *)malloc(512000 * sizeof(char));
            scanf("%s", s);
            int result_size;
            char* result = isBalanced(s);
            printf("%s\n", result);
        }
        return 0;
    }