<p>Given an expression such as <code>expression = &quot;e + 8 - a + 5&quot;</code> and an evaluation map such as <code>{&quot;e&quot;: 1}</code> (given in terms of <code>evalvars = [&quot;e&quot;]</code> and <code>evalints = [1]</code>), return a list of tokens representing the simplified expression, such as <code>[&quot;-1*a&quot;,&quot;14&quot;]</code></p>

<ul>
	<li>An expression alternates chunks and symbols, with a space separating each chunk and symbol.</li>
	<li>A chunk is either an expression in parentheses, a variable, or a non-negative integer.</li>
	<li>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 <code>&quot;2x&quot;</code> or <code>&quot;-x&quot;</code>.</li>
</ul>

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

<ul>
	<li>For example, <code>expression = &quot;1 + 2 * 3&quot;</code> has an answer of <code>[&quot;7&quot;]</code>.</li>
</ul>

<p>The format of the output is as follows:</p>

<ul>
	<li>For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically.
	<ul>
		<li>For example, we would never write a term like <code>&quot;b*a*c&quot;</code>, only <code>&quot;a*b*c&quot;</code>.</li>
	</ul>
	</li>
	<li>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.
	<ul>
		<li>For example, <code>&quot;a*a*b*c&quot;</code> has degree <code>4</code>.</li>
	</ul>
	</li>
	<li>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.</li>
	<li>An example of a well-formatted answer is <code>[&quot;-2*a*a*a&quot;, &quot;3*a*a*b&quot;, &quot;3*b*b&quot;, &quot;4*a&quot;, &quot;5*c&quot;, &quot;-6&quot;]</code>.</li>
	<li>Terms (including constant terms) with coefficient <code>0</code> are not included.
	<ul>
		<li>For example, an expression of <code>&quot;0&quot;</code> has an output of <code>[]</code>.</li>
	</ul>
	</li>
</ul>

<p><strong>Note:</strong> You may assume that the given expression is always valid. All intermediate results will be in the range of <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> expression = &quot;e + 8 - a + 5&quot;, evalvars = [&quot;e&quot;], evalints = [1]
<strong>Output:</strong> [&quot;-1*a&quot;,&quot;14&quot;]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> expression = &quot;e - 8 + temperature - pressure&quot;, evalvars = [&quot;e&quot;, &quot;temperature&quot;], evalints = [1, 12]
<strong>Output:</strong> [&quot;-1*pressure&quot;,&quot;5&quot;]
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> expression = &quot;(e + 8) * (e - 8)&quot;, evalvars = [], evalints = []
<strong>Output:</strong> [&quot;1*e*e&quot;,&quot;-64&quot;]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= expression.length &lt;= 250</code></li>
	<li><code>expression</code> consists of lowercase English letters, digits, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, <code>&#39;*&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, <code>&#39; &#39;</code>.</li>
	<li><code>expression</code> does not contain any leading or trailing spaces.</li>
	<li>All the tokens in <code>expression</code> are separated by a single space.</li>
	<li><code>0 &lt;= evalvars.length &lt;= 100</code></li>
	<li><code>1 &lt;= evalvars[i].length &lt;= 20</code></li>
	<li><code>evalvars[i]</code> consists of lowercase English letters.</li>
	<li><code>evalints.length == evalvars.length</code></li>
	<li><code>-100 &lt;= evalints[i] &lt;= 100</code></li>
</ul>

bool isOpCode(char c) {
    return c == '+' || c == '-' || c == '*' || c == '(' || c == ')';
}

bool isConstant(string s) {
    if (s[0] == '-') {
        s = s.substr(1);
    }
    for (int i = 0; i < s.length(); i++) {
        if (s[i] < '0' || s[i] > '9') {
            return false;
        }
    }
    return true;
}

// A term is the result of multipling a constant (coef) and one or more identifiers.
class Term {
public:
    // e.g. term 2*a^2*b will have
    // "a" => 2
    // "b" => 1
    // coef = 2
    map<string, int> varOrder;
    int coef;

    Term() {
        coef = 1;
    }

    string toString() {
        string s = to_string(coef) + "*";
        for (auto p : varOrder) {
            s += p.first + to_string(p.second);
        }
        return s;
    }

    // 2*a^2*b^3 will get id as "a2b3".
    // -2*a^2*b^3 will also get id as "a2b3".
    string getId() {
        string id = "";
        for (auto p : varOrder) {
            id += p.first + std::to_string(p.second);
        }
        return id;
    }

    void multiplyVar(string& s, unordered_map<string,int> &varMap) {
        if (isConstant(s)) {
            int multiplier = stoi(s);
            coef = coef * multiplier;
        } else if (varMap.find(s) != varMap.end()) {
            int multiplier = varMap[s];
            coef = coef * multiplier;
        } else {
            varOrder[s] += 1;
        }
    }

    void multiplyTerm(Term& term) {
        coef = coef * term.coef;
        for (auto p : term.varOrder) {
            varOrder[p.first] += p.second;
        }
    }

    void addTerm(Term& term) {
        coef = coef + term.coef;
    }

    int getOrder() {
        int order = 0;
        for (auto p : varOrder) {
            order += p.second;
        }
        return order;
    }
};

// An expression is the result of adding one or more terms or constants
class Expression {
public:
    vector<Term> terms;
    int coef;

    Expression() {
        coef = 1;
    }

    string toString() {
        string s = "";
        for (auto t : terms) {
            s += "+" + t.toString();
        }
        return s;
    }

    void addVar(string var, unordered_map<string, int> &varMap) {
        Term t;
        t.multiplyVar(var, varMap);
        terms.push_back(t);
    }

    void multiplyVar(string var, unordered_map<string, int> &varMap) {
        for (auto& term : terms) {
            term.multiplyVar(var, varMap);
        }
    }

    void multiplyExpr(Expression& expr) {
        if (terms.size() == 0) {
            terms = expr.terms;
            return;
        } else if (expr.terms.size() == 0) {
            return;
        }

        unordered_map<string, Term> newTerms;
        for (int i = 0; i < terms.size(); i++) {
            for (int j = 0; j < expr.terms.size(); j++) {
                Term a = terms[i];
                Term& b = expr.terms[j];
                a.multiplyTerm(b);
                string newTermId = a.getId();
                if (newTerms.find(newTermId) == newTerms.end()) {
                    newTerms[newTermId] = a;
                } else {
                    newTerms[newTermId].addTerm(a);
                }
            }
        }
        terms.clear();
        for (auto p : newTerms) {
            terms.push_back(p.second);
        }
    }

    void addExpr(Expression& expr, unordered_map<string, int> &varMap) {
        unordered_map<string, Term> newTerms;
        for (int i = 0; i < terms.size(); i++) {
            Term& a = terms[i];
            string id = a.getId();
            newTerms[id] = a;
        }

        string negateCoef = "-1";
        for (int j = 0; j < expr.terms.size(); j++) {
            Term b = expr.terms[j];
            string id = b.getId();
            if (expr.coef == -1) {
                b.multiplyVar(negateCoef, varMap);
            }
            if (newTerms.find(id) == newTerms.end()) {
                newTerms[id] = b;
            } else {
                newTerms[id].addTerm(b);
            }
        }
        terms.clear();
        for (auto p : newTerms) {
            terms.push_back(p.second);
        }
    }
};

class Parser {
public:
    unordered_map<string, int> varMap;
    string expression;
    int cursor;

    Parser(string _expression, vector<string> &evalvars, vector<int> &evalints) {
        for (int i = 0; i < evalvars.size(); i++) {
            varMap[evalvars[i]] = evalints[i];
        }
        cursor = 0;

        // Remove all white space from expression
        expression = "";
        for (char c : _expression) {
            if (c != ' ') {
                expression += c;
            }
        }
    }

    Expression run() {
        vector<Expression> baseExprs;
        vector<Expression> currExprs;
        Expression baseExpr;
        Expression currExpr;
        while (cursor < expression.length()) {
            char c = expression[cursor];
            if (!isOpCode(c)) {
                string identifier = getIdentifier();
                cursor += identifier.length();
                if (currExpr.terms.size() == 0) {
                    currExpr.addVar(identifier, varMap);
                } else {
                    currExpr.multiplyVar(identifier, varMap);
                }
            } else {
                if (c == '+') {
                    baseExpr.addExpr(currExpr, varMap);
                    cursor += 1;
                    currExpr = Expression();
                } else if (c == '-') {
                    baseExpr.addExpr(currExpr, varMap);
                    cursor += 1;
                    currExpr = Expression();
                    currExpr.coef = -1;
                } else if (c == '*') {
                    cursor += 1;
                } else if (c == '(') {
                    baseExprs.push_back(baseExpr);
                    currExprs.push_back(currExpr);
                    baseExpr = Expression();
                    currExpr = Expression();
                    cursor += 1;
                } else if (c == ')') {
                    baseExpr.addExpr(currExpr, varMap);
                    if (currExprs.size() > 0) {
                        currExprs.back().multiplyExpr(baseExpr);
                        currExpr = currExprs.back();
                        currExprs.pop_back();
                        baseExpr = baseExprs.back();
                        baseExprs.pop_back();
                    }
                    cursor += 1;
                }
            }
        }

        baseExpr.addExpr(currExpr, varMap);
        sort(baseExpr.terms.begin(), baseExpr.terms.end(), [](Term& a, Term& b) {
            int orderA = a.getOrder();
            int orderB = b.getOrder();
            if (orderA != orderB) {
                return orderA < orderB;
            }
            string idA = a.getId();
            string idB = b.getId();
            return idA < idB;
        });
        return baseExpr;
    }

    string getIdentifier() {
        int i = cursor;
        string s;
        for (; i < expression.length(); i++) {
            if (isOpCode(expression[i])) {
                break;
            }
        }
        string id = expression.substr(cursor, i - cursor);
        return id;
    }
};

Expression myBasicCalculatorIV(string expression, vector<string>& evalvars, vector<int>& evalints) {
    Parser parser(expression, evalvars, evalints);
    Expression e = parser.run();
    return e;
}

// Generic code above

string getStupidStringFormatLeetcodeWants(Term &term) {
    string s = "";
    for (auto p : term.varOrder) {
        for (int i = 0; i < p.second; i++) {
            s += "*" + p.first;
        }
    }
    return s;
}

class Solution {
    struct Item {
        int order;
        int coef;
        string varStr;
    };
public:
    vector<string> basicCalculatorIV(string expression, vector<string>& evalvars, vector<int>& evalints) {
        Expression e = myBasicCalculatorIV(expression, evalvars, evalints);

        vector<Item> items;
        for (auto &term : e.terms) {
            if (term.coef == 0) {
                continue;
            }
            int order = term.getOrder();
            int coef = term.coef;
            string varStr = getStupidStringFormatLeetcodeWants(term);
            items.push_back({ order, coef, varStr });
        }

        sort(items.begin(), items.end(), [](Item &a, Item &b) {
            if (a.order != b.order) {
                return a.order > b.order;
            }
            return a.varStr < b.varStr;
        });
        
        vector<string> result;

        for (auto &item : items) {
            string coefStr = to_string(item.coef);
            result.push_back(coefStr + item.varStr);
        }
        
        return result;
    }
};
24300