# 770. Basic Calculator IV

Given an expression such as `expression = "e + 8 - a + 5"` and an evaluation map such as `{"e": 1}` (given in terms of `evalvars = ["e"]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `["-1*a","14"]`

• An expression alternates chunks and symbols, with a space separating each chunk and symbol.
• A chunk is either an expression in parentheses, a variable, or a non-negative integer.
• A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like `"2x"` or `"-x"`.

Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction.

• For example, `expression = "1 + 2 * 3"` has an answer of `["7"]`.

The format of the output is as follows:

• For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically.
• For example, we would never write a term like `"b*a*c"`, only `"a*b*c"`.
• Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.
• For example, `"a*a*b*c"` has degree `4`.
• The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed.
• An example of a well-formatted answer is `["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"]`.
• Terms (including constant terms) with coefficient `0` are not included.
• For example, an expression of `"0"` has an output of `[]`.

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"]
``````

Example 4:

``````Input: expression = "a * b * c + b * a * c * 4", evalvars = [], evalints = []
Output: ["5*a*b*c"]
``````

Example 5:

``````Input: expression = "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))", evalvars = [], evalints = []
Output: ["-1*a*a*b*b","2*a*a*b*c","-1*a*a*c*c","1*a*b*b*b","-1*a*b*b*c","-1*a*b*c*c","1*a*c*c*c","-1*b*b*b*c","2*b*b*c*c","-1*b*c*c*c","2*a*a*b","-2*a*a*c","-2*a*b*b","2*a*c*c","1*b*b*b","-1*b*b*c","1*b*c*c","-1*c*c*c","-1*a*a","1*a*b","1*a*c","-1*b*c"]
``````

Constraints:

• `1 <= expression.length <= 250`
• `expression` consists of lowercase English letters, digits, `'+'``'-'``'*'``'('``')'``' '`.
• `expression` does not contain any leading or trailing spaces.
• All the tokens in `expression` are separated by a single space.
• `0 <= evalvars.length <= 100`
• `1 <= evalvars[i].length <= 20`
• `evalvars[i]` consists of lowercase English letters.
• `evalints.length == evalvars.length`
• `-100 <= evalints[i] <= 100`

``````class Solution {
public:
vector<string> basicCalculatorIV(string expression, vector<string>& evalvars, vector<int>& evalints) {
vector<string> res;
unordered_map<string, int> evalMap;
for (int i = 0; i < evalvars.size(); ++i) {
evalMap[evalvars[i]] = evalints[i];
}
auto t = helper(expression, evalMap);
for (auto &a : t) {
if (a.second == 0) continue;
res.push_back(to_string(a.second));
for (auto &p : a.first) res.back() += "*" + p;
}
return res;
}

private:
struct cmp {
bool operator() (const vector<string>& a, const vector<string>& b) const {
if (a.size() == b.size()) return a < b;
return a.size() > b.size();
}
};

map<vector<string>, int, cmp> helper(string expr, unordered_map<string, int>& evalMap) {
map<vector<string>, int, cmp> local{{{}, 1}}, res;
string sub;
for (int i = 0, sign = 1, n = expr.size(); i <= n; ++i) {
if (i < n && expr[i] == ' ') continue;
if (i < n && isalnum(expr[i])) sub += expr[i];
else if (i < n && expr[i] == '(') {
++i;
for (int cnt = 1; ; ++i) {
if (expr[i] == '(') ++cnt;
else if (expr[i] == ')') --cnt;
if (cnt == 0) break;
sub += expr[i];
}
} else { // '+', '-', '*' or i == n
if (sub.size() == n) {
if (evalMap.count(sub)) return {{{}, evalMap[sub]}};
if (isdigit(sub[0])) return {{{}, stoi(sub)}};
return {{{sub}, 1}};
}
map<vector<string>, int, cmp> mult, t = helper(sub, evalMap);
for (auto &a : local) {
for (auto &b : t) {
auto k = a.first;
k.insert(k.end(), b.first.begin(), b.first.end());
sort(k.begin(), k.end());
mult[k] += a.second * b.second;
}
}
local = move(mult);
if (i == n || expr[i] != '*') { // '+' or '-'
for (auto &a : local) {
res[a.first] += sign * a.second;
}
sign = (i < n && expr[i] == '-') ? -1 : 1;
local = {{{}, 1}};
}
sub = "";
}
}
return res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/770

Basic Calculator III

Basic Calculator II

Basic Calculator

https://leetcode.com/problems/basic-calculator-iv/

https://leetcode.com/problems/basic-calculator-iv/discuss/113550/C++-relatively-concise-solution...

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation