It is necessary that with this arrangement of brackets: (15 * 4) + 3, the brackets are deleted => 15 * 4 + 3. If the brackets do not make sense, they are deleted.

Example: (5 + 5) + 4 => 5 + 5 + 4

I tried to do it in C, but I need to write in Java. The code does not work, I do not know why.

void main(){ char *num = "15+(5*A)/(2+B)+C*(2-(A + B))"; int i, j, mark, bol = 0; for (i = 0; i < 29; i++){ if (num[i] == "(" && bol == 0){ printf("\n%s", num); mark = i - 1; bol = 1; } else if (num[i] == "+" && num[mark] == "+" && bol == 1){ num[mark + 1] = ""; bol = 2; } else if (num[i] == "*" && (num[mark] == "-" || num[mark] == "+") && bol == 1){ num[mark + 1] = ""; bol = 2; } else if (num[i] == ")" && bol == 2){ num[i] = ""; bol = 0; } } printf("\n%s", num); } 

Himself made in java

 public class TestMinimalParen { private static String check_brackets(String theExpressionText){ char str[] = theExpressionText.toCharArray(); int bool = 0, b_Brackets = 0, f_br = 0, l_br = 0, mark = 0; for (int i = 0; i < str.length; i++) { if (bool == 0 && str[i] == '('){ f_br = i; bool = 1; } else if (bool == 1 && str[i] == '+' || str[i] == '-' || str[i] == '*'){ mark = i; bool = 2; } else if (bool == 1 && str[i] == '('){ f_br = i; } else if (bool == 2 && str[i] == ')'){ l_br = i; bool = 3; } else if (bool == 3 && str[f_br] != '?' && str[l_br] != '?'){ b_Brackets = 0; if (str[f_br - 1] == '+' && str[mark] == '+' && str[l_br + 1] == '+') { b_Brackets = 1; } else if (str[f_br - 1] == '+' && str[mark] == '+' && (str[l_br + 1] == '/' || l_br + 1 > str.length)){ b_Brackets = 1; } else if ((str[f_br - 1] == '/' || f_br - 1 <= 0) && str[mark] == '+' && str[l_br + 1] == '+'){ b_Brackets = 1; } else if ((str[f_br - 1] == '+' || str[f_br - 1] == '-') && str[mark] == '*' && (str[l_br + 1] == '+' || str[l_br + 1] == '-')){ b_Brackets = 1; } else if ((str[f_br - 1] == '/' || f_br - 1 <= 0) && str[mark] == '*' && (str[l_br + 1] == '+' || str[l_br + 1] == '-')){ b_Brackets = 1; } else if ((str[f_br - 1] == '+' || str[f_br - 1] == '-') && str[mark] == '*' && (str[l_br + 1] == '/' || l_br + 1 < str.length)){ b_Brackets = 1; } else if ((str[f_br - 1] == '/' || f_br - 1 <= 0) && (str[l_br + 1] == '/' || l_br + 1 < str.length)){ b_Brackets = 1; } if (b_Brackets == 1){ str[f_br] = '?'; str[l_br] = '?'; } bool = 0; } } String fin = ""; for (int i = 0; i < str.length; i++){ if (str[i] != '?'){ String f = Character.toString(str[i]); fin = fin + f; } } return fin; } 
  • one
    You are moving in the wrong direction. First you need to parse the expression into an intermediate representation and work with it. Here is a quick google for JS, but the principles will be the same everywhere. medium.freecodecamp.org/… (see second section, about AST) - rjhdby
  • one
    1. Parsim all vyradenie. 2. Write the expression again. - Qwertiy

0