![]() |
VOOZH | about |
Given two expressions in the form of strings. The task is to compare them and check if they are similar. Expressions consist of lowercase alphabets, '+', '-' and '( )'.
Examples:
Input : exp1 = "-(a+b+c)"
exp2 = "-a-b-c"
Output : Yes
Explanation : The first expression, when simplified by distributing the negative sign, matches the second expression, hence they are similar.Input : exp1 = "-(c+b+a)"
exp2 = "-c-b-a"
Output : Yes
Explanation : The order of terms inside parentheses does not affect the result, and distributing the negative sign yields a match, so the expressions are similar.Input : exp1 = "a-b-(c-d)"
exp2 = "a-b-c-d"
Output : No
Explanation : The negative sign distribution inside the parentheses leads to different signs for the terms, making the expressions not similar.
This approach tracks the global and local signs in an expression. The global sign affects operands within parentheses, while the local sign applies to each operand individually. The final sign of an operand is the product of its local and global signs.
For example, in
a + b - (c - d), the expression evaluates toa + b - c + d, where the global sign inside parentheses flips the signs ofcandd.A stack keeps track of global signs, and a count vector records operand counts. Both expressions are evaluated in opposite ways, and if the count vector ends with all zeros, the expressions are considered equivalent.
Yes