#770

Basic Calculator IV

candidate master · 1500 · lc hard +32 · verified · 49.8% accepted · 181 likes · top 37%

Description

Simplify a mathematical expression string after substituting known variables from evalvars / evalints and return the symbolic result as a list of tokens.

The expression uses standard operator precedence (parentheses, then multiplication, then addition/subtraction). Variables are lowercase-letter strings; they are never given a leading coefficient or unary minus. The output format rules are:

- Each term's free variables are listed in sorted lexicographic order, e.g., "a*b*c" not "b*a*c".

- Terms are ordered by descending degree (number of variable factors, counting multiplicity), with ties broken lexicographically.

- The coefficient always appears as the leading factor, e.g., "3*a*b" or "-6". A coefficient of 1 is still printed.

- Terms with a zero coefficient are omitted.

All intermediate values fit in a 32-bit integer and the expression is guaranteed valid.

Example 1:

Input: expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
Output: ["-1*a","14"]

Example 2:

Input: expression = "e - 8 + temperature - pressure", evalvars = ["e", "temperature"], evalints = [1, 12]
Output: ["-1*pressure","5"]

Example 3:

Input: expression = "(e + 8) * (e - 8)", evalvars = [], evalints = []
Output: ["1*e*e","-64"]

Code

1
2
3