1012. Remove Brackets from an Algebraic Expression

You are given an algebraic expression as a string. The expression contains lowercase English alphabets, plus (+) and minus (-) signs, and brackets ( and ). Your task is to simplify the expression by removing all brackets, taking care to apply the correct signs to all elements inside the brackets.

Implement a function that removes all brackets from the expression while preserving the algebraic correctness of the expression.

Example 1:

Input: expression = "a+((b-c)+d)"

Output: "a+b-c+d"

Explanation: Removed all brackets while preserving the correct signs.

Example 2:

Input: expression = "(((a-b))+c)"

Output: "a-b+c"

Explanation: Brackets removed, inner signs preserved.

Now Your Turn!

Pick the correct output for the given input

Input: expression = "a-(b-c-(d+e))-f"

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The input expression will be a non-empty string of length at most 105.
  • The expression will be valid, meaning:
  • All parentheses will be balanced.
  • No numbers or multiplication/division will appear.
  • All operators are binary (+ or -) and operands are lowercase letters.
0
class Solution {
public:
string removeBrackets(const string& expr) {
// Your code goes here
}
};
 
Test Case

Input:

Expression