• + 0 comments

    In C language, not using a stack but mimicking it:

    char* isBalanced(char* s) {
        char* s2 = malloc(strlen(s) * sizeof(char));
        memset(s2, strlen(s), sizeof(char)); // Not mandatory. To keep memory clean
        
        char* p1 = s;
        char* p2 = s2;
        
        bool isBalanced = true;
        
        while (isBalanced && *p1)
        {
            switch (*p1)
            {
                case '{':
                case '(':
                case '[':
                    *(p2++) = *p1;
                    break;
                case '}':
                    if (p2 > s2 && *(p2 - 1) == '{')
                        *(--p2) = '\0';
                    else
                        isBalanced = false;
                    break;
                case ')':
                    if (p2 > s2 && *(p2 - 1) == '(')
                        *(--p2) = '\0';
                    else
                        isBalanced = false;
                    break;
                case ']':
                    if (p2 > s2 && *(p2 - 1) == '[')
                        *(--p2) = '\0';
                    else
                        isBalanced = false;
                    break;
            }
            
            p1++;
        }
        
        if (*p1 == '\0' && p2 > s2)
            isBalanced = false;
        
        free(s2);
        
        char * response = malloc(4 * sizeof(char));
        if (isBalanced)
            strcpy(response, "YES");
        else
            strcpy(response, "NO");
        return response;
    }