top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to check if expression has redundant braces using C?

+2 votes
488 views

((a+b)) has redundant braces so answer should be 1
(a + (a + b)) doesn't have have any redundant braces so answer should be 0

posted Dec 4, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
#include<bits/stdc++.h>
#define FOR(i,n) for(int i = 0; i < n; i++)
using namespace std;

void solve(string& str, int n) {

    int counter = 0;
    int i = 0;
    char delim = '.';
    stack<char> stk;

    while(i < n) {

        if(str[i] == '(') {

            stk.push(str[i]);
            if(str[i+1] == '(') stk.push(delim);
        }

        else if(str[i] == ')') {

            if(stk.top() == delim && (str[i+1] == ')' || str[i+1] == '\0')) {

                stk.pop();
                counter++;
            }

            stk.pop();
            if(str[i+1] != ')' && !stk.empty() && stk.top() == delim) stk.pop();
        }

        else {

            if(!stk.empty() && str[i-1] == '(' && str[i+1] == ')') counter++;

        }

        i++;
    }
    cout << counter << endl << endl;
}

int main() {

    string str = "(((A)+(B)+C*(D+C)))";
    cout << str << endl;
    solve(str, str.length());

    str = "((A)+(B))";
    cout << str << endl;
    solve(str, str.length());

    str = "(A+B)";
    cout << str << endl;
    solve(str, str.length());

    str = "((A+B))";
    cout << str << endl;
    solve(str, str.length());

    str = "(A)+(B)";
    cout << str << endl;
    solve(str, str.length());


    str = "((A+C)+(B+D))";
    cout << str << endl;
    solve(str, str.length());

    return 0;
}
answer Dec 7, 2015 by Shivaranjini
...