Bracket Validation Problem

 avatar
unknown
c_cpp
a year ago
1.6 kB
4
Indexable
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 30

char stack[MAX_SIZE];
int top = -1;

void push(char);
void pop();
int eval(char[]);
int main()
{
    char expr[MAX_SIZE];
    int result;
   
    printf("\n Enter the expression: ");
    scanf("%[^\n]s", expr);
   
    printf("\n The input string is: %s", expr);
    result = eval(expr);
   
    if (result)
        printf("\n It is a valid expression.");
    else
        printf("\n It is an invalid expression.");
   
    return 0;
}

int eval(char expr[])
{
    int i = 0, valid;
    char ch;
   
    while (expr[i] != '\0')
    {
        ch = expr[i];
       
        if (ch == '(' || ch == '[' || ch == '{')
        {
            push(ch);
        }
        else if (ch == ')' || ch == ']' || ch == '}')
        {
            if (top == -1)
            {
                return 0;
            }
           
            char topBracket = stack[top];
           
            if ((ch == ')' && topBracket == '(') ||
                (ch == ']' && topBracket == '[') ||
                (ch == '}' && topBracket == '{'))
            {
                pop();
            }
            else
            {
                return 0;
            }
        }
       
        i++;
    }
   
    if (top == -1)
        valid = 1;
    else
        valid = 0;
   
    return valid;
}

void push(char ch)
{
    if (top < MAX_SIZE - 1)
    {
        top++;
        stack[top] = ch;
    }
   
}

void pop()
{
    if (top >= 0)
    {
        top--;
    }
   
}

/*
 Enter the expression: exp = " [()]{}{[()()]()} "

 The input string is: exp = " [()]{}{[()()]()} "
 It is a valid expression.
*/
Editor is loading...
Leave a Comment