Use the C++ precedence rules to remove any unnecessary parenthesis from the following expressions :
A. ((a* b)) + (c * d))
B. ((a* b) / (c * d))
C. ((a + b) + ((c / (d + e)) * f))
D. (((a + b) / (c + d))* (e + f))
E. ((-a + b) <= (c * d)) && ((a + b) >= (c - d))
#include <bits/stdc++.h>
#include<iostream>
#include <stdio.h>
#include <string>
#include <set>
#include <stack>
using namespace std;
int Count;
std::string CheckExp(std::string InputStr, int tempCount)
{
std::set<char> Op = {'+', '-', '*', '/'};
std::string expression;
std::set<char> op;
Count = tempCount;
while (true) {
if (InputStr[Count] == '(')
{
expression += CheckExp(InputStr, Count + 1);
} else if (InputStr[Count] == ')') {
if ((InputStr[Count + 1] != '*') && (InputStr[Count + 1] != '/')) return expression;
else
{
if ((op.find('+') == op.end()) && (op.find('-') == op.end())) return expression;
else return '(' + expression + ')';
}
}
else
{
char temp = InputStr[Count];
expression = expression + temp;
if (Op.find(temp) != Op.end()) op.insert(temp);
}
Count++;
if (Count >= InputStr.size()) break;
}
return expression;
}
int main()
{
std::string s1("((a* b)) + (c * d))");
std::cout << CheckExp(s1, 0)<<endl;
std::string s2("((a* b) / (c * d))");
std::cout << CheckExp(s2, 0)<<endl;
std::string s3("((a + b) + ((c / (d + e)) * f))");
std::cout << CheckExp(s3, 0)<<endl;
std::string s4("(((a + b) / (c + d))* (e + f)");
std::cout << CheckExp(s4, 0)<<endl;
std::string s5("((-a + b) <= (c * d)) && ((a + b) >= (c - d))");
std::cout << CheckExp(s5, 0)<<endl;
return 0;
}
Comments
Leave a comment