Removing brackets from an algebraic expression

Write a program to remove the brackets from an algebraic expression.

Example:

Input:  str[] = "{(a+b)+d+e+(e*f)}
Output: String after remove of brackets is a+b+d+e+e*f

Approach

C

#include <stdio.h>
#include <string.h>

int main()
{
    char str[] = "{(a+b)+d+e+(e*f)}";
    char newString[1000];

    int n = strlen(str);

    int len = 0i = 0;
    while (i < n)
    {
        if (str[i] == '(' || str[i] == ')')
        {
            i++;
        }
        else if (str[i] == '{' || str[i] == '}')
        {
            i++;
        }
        else if (str[i] == '[' || str[i] == ']')
        {
            i++;
        }
        else
        {
            newString[len] = str[i];
            i++;
            len++;
        }
    }
    newString[len] = '\0';
    printf("String after remove of brackets is %s"newString);
    return 0;
}
C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str = "{(a+b)+d+e+(e*f)}";

    int n = str.size();

    int len = 0i = 0;
    while (i < n)
    {
        if (str[i] == '(' || str[i] == ')')
        {
            i++;
        }
        else if (str[i] == '{' || str[i] == '}')
        {
            i++;
        }
        else if (str[i] == '[' || str[i] == ']')
        {
            i++;
        }
        else
        {
            str[len] = str[i];
            i++;
            len++;
        }
    }
    str.resize(len);
    cout << "String after remove of brackets is " << str;
    return 0;
}


No comments:

Post a Comment