You are given a string expression representing a Lisp-like expression to return the integer value of.

The syntax for these expressions is given as follows.


	An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
	(An integer could be positive or negative.)
	A let expression takes the form "(let v1 e1 v2 e2 ... vn en expr)", where let is always the string "let", then there are one or more pairs of alternating variables and expressions, meaning that the first variable v1 is assigned the value of the expression e1, the second variable v2 is assigned the value of the expression e2, and so on sequentially; and then the value of this let expression is the value of the expression expr.
	An add expression takes the form "(add e1 e2)" where add is always the string "add", there are always two expressions e1, e2 and the result is the addition of the evaluation of e1 and the evaluation of e2.
	A mult expression takes the form "(mult e1 e2)" where mult is always the string "mult", there are always two expressions e1, e2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2.
	For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names "add", "let", and "mult" are protected and will never be used as variable names.
	Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.


&nbsp;
Example 1:

Input: expression = "(let x 2 (mult x (let x 3 y 4 (add x y))))"
Output: 14
Explanation: In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.


Example 2:

Input: expression = "(let x 3 x 2 x)"
Output: 2
Explanation: Assignment in let statements is processed sequentially.


Example 3:

Input: expression = "(let x 1 y 2 x (add x y) (add x y))"
Output: 5
Explanation: The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.


&nbsp;
Constraints:


	1 &lt;= expression.length &lt;= 2000
	There are no leading or trailing spaces in expression.
	All tokens are separated by a single space in expression.
	The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.
	The expression is guaranteed to be legal and evaluate to an integer.


class Solution:
    def evaluate(self, expression: str) -> int:
        loc = {}
        stack = []
        for i, x in enumerate(expression): 
            if x == "(": stack.append(i)
            elif x == ")": loc[stack.pop()] = i
        
        def fn(lo, hi, mp): 
            """Return value of given expression."""
            if expression[lo] == "(": return fn(lo+1, hi-1, mp)
            i = lo
            vals = []
            while i < hi: 
                if expression[i:i+3] in ("let", "add"): 
                    op = expression[i:i+3]
                    i += 3
                elif expression[i:i+4] == "mult": 
                    op = "mult"
                    i += 4
                elif expression[i].isalpha(): 
                    x = ""
                    while i < hi and expression[i].isalnum(): 
                        x += expression[i]
                        i += 1
                    if op in ("add", "mult"): vals.append(mp[x])
                elif expression[i].isdigit() or expression[i] == "-": 
                    v = ""
                    while i < hi and (expression[i].isdigit() or expression[i] == "-"): 
                        v += expression[i]
                        i += 1
                    if op == "let": mp[x] = int(v)
                    else: vals.append(int(v))
                elif expression[i] == "(": 
                    v = fn(i+1, loc[i], mp.copy())
                    i = loc[i] + 1
                    if op == "let": mp[x] = v
                    else: vals.append(v)
                else: i += 1
            if op == "let": return int(v)
            elif op == "add": return sum(vals)
            else: return reduce(mul, vals)
            
        return fn(0, len(expression), {})
class Solution {
    
    String expression;
    int index;
    HashMap<String,Deque<Integer>> scope; 
    //variable may be assigned many times, we use the peek value 
    
    public int evaluate(String expression) {
        this.expression=expression;
        index=0;
        scope=new HashMap<>();
        return evaluate();
    }
    
    private int evaluate(){
        
        if(expression.charAt(index)=='('){
            //this is an expression
            index++; //skip '('
            char begin=expression.charAt(index);
            int ret;
            if(begin=='l'){
                //let
                index += 4; //skip let and a blank space
                ArrayList<String> vars=new ArrayList<>();
                while(true){
                    if(!Character.isLowerCase(expression.charAt(index))){
                        ret=evaluate();
                        break;
                    }
                    String var=parseVar();
                    if(expression.charAt(index)==')'){
                        ret=scope.get(var).peek();
                        break;
                    }
                    vars.add(var);
                    index++;
                    int e=evaluate();
                    scope.putIfAbsent(var, new LinkedList<>());
                    scope.get(var).push(e); //assign a new value
                    index++;
                }
                for (String var : vars) {
                    scope.get(var).pop(); // remove all values of this scope
                }

            } else if(begin=='a') {
                //add
                index += 4;
                int v1 = evaluate();
                index++;
                int v2 = evaluate();
                ret = v1+v2;
            } else {
                //multi
                index += 5;
                int v1 = evaluate();
                index++;
                int v2 = evaluate();
                ret =  v1*v2;
            }
            index++; // skip ')'
            return ret;
        } else {
            //this is not a expression, this is an integer or a variable
            if(Character.isLowerCase(expression.charAt(index))){
				//this is a variable, the current value is peek value
                String var=parseVar();
                return scope.get(var).peek();
            } else {
				//this is an integer
                return parseInt();
            }
        }
    }
    
    //read an integer
    private int parseInt(){
        boolean negative=false;
        if(expression.charAt(index)=='-'){
            negative=true;
            index++;
        }
        int ret=0;
        while(Character.isDigit(expression.charAt(index))){
            ret*=10;
            ret+=expression.charAt(index)-'0';
            index++;
        }
        if(negative) return -ret;
        return ret;
    }
    
    //read a variable
    private String parseVar(){
        StringBuilder sb=new StringBuilder();
        char c=expression.charAt(index);
        while(c!=' ' && c!=')'){
            sb.append(c);
            c=expression.charAt(++index);
        }
        return sb.toString();
    }
}
class Context {
  unordered_map<string_view, int> _map;
  const Context *_parent{};
  public:
  Context(const Context *parent) : _parent{parent}
  {
    ;
  }
  const Context* Parent() const { return _parent; }
  int GetValue(const string_view &key) const
  {
    auto it = _map.find(key);
    if (it != _map.end()) return it->second;
    if (_parent) return _parent->GetValue(key);
    assert(0);
    return numeric_limits<int>::min();
  }
  void AddValue(const string_view &key, int val) {
    auto [it, isInserted] = _map.emplace(key, val);
    if (!isInserted) it->second = val;
  }
};
class Solution {
  string_view symbol(string_view &expr) {
    string_view ret;
    if (expr.empty() || !isalpha(expr[0])) {
      return ret;
    }
    auto pos = expr.find_first_of(" )");
    assert(pos != string_view::npos);
    ret = expr.substr(0, pos);
    expr.remove_prefix(pos);
    return ret;
  }
  int evaluate(string_view &expr, Context *context) {
    assert(!expr.empty());
    if (expr[0] == '(') {
      assert(expr.length() >= 4);
      if (expr.substr(0, 4) == "(add") {
        assert(expr.length() > 4);
        expr.remove_prefix(4);
        assert(!expr.empty() && expr[0] == ' ');
        expr.remove_prefix(1);
        int l = evaluate(expr, context);
        assert(!expr.empty() && expr[0] == ' ');
        expr.remove_prefix(1);
        int r = evaluate(expr, context);
        assert(!expr.empty() && expr[0] == ')');
        expr.remove_prefix(1);
        return l + r;
      }
      if (expr.substr(0, 4) == "(mul") {
        assert(expr.length() > 5);
        expr.remove_prefix(5);
        assert(!expr.empty() && expr[0] == ' ');
        expr.remove_prefix(1);
        int l = evaluate(expr, context);
        assert(!expr.empty() && expr[0] == ' ');
        expr.remove_prefix(1);
        int r = evaluate(expr, context);
        assert(!expr.empty() && expr[0] == ')');
        expr.remove_prefix(1);
        return l * r;
      }
      if (expr.substr(0, 4) == "(let") {
        assert(expr.length() > 4);
        expr.remove_prefix(4);
        Context nc(context);
        while (1) {
          assert(!expr.empty() && expr[0] == ' ');
          expr.remove_prefix(1);
          string_view sym = symbol(expr);
          assert(!expr.empty());
          if (sym.empty() || expr[0] == ')') {
            int ret{};
            if (sym.empty()) {
              ret = evaluate(expr, &nc);
            } else {
              ret = nc.GetValue(sym);
            }
            assert(!expr.empty() && expr[0] == ')');
            expr.remove_prefix(1);
            return ret;
          }
          assert(!expr.empty() && expr[0] == ' ');
          expr.remove_prefix(1);
          int value = evaluate(expr, &nc);
          nc.AddValue(sym, value);
        }
        assert(0);
      }
    } 
    if (isdigit(expr[0]) || expr[0] == '-') {
      auto pos = expr.find_first_not_of("-0123456789");
      auto len = min(expr.length(), pos);
      int num;
      if (auto [ptr, ec] = from_chars(expr.data(), expr.data()+len, num); ec == errc()) {
        expr.remove_prefix(len);
      } else {
        assert(0);
      }
      return num;
    }
    if (isalpha(expr[0])) {
      string_view sym = symbol(expr);
      assert(!expr.empty() && (expr[0] == ' ' || expr[0] == ')'));
      return context->GetValue(sym);
    }
    assert(0);
    return numeric_limits<int>::min();
  }
public:
    int evaluate(string expression) {
      string_view expr(expression);
      Context context(nullptr);
      return evaluate(expr, &context);
    }
};
/**
 * @param {string} expression
 * @return {number}
 */
var evaluate = function(expression) {
    return helper(expression);
};

const helper = (expr, map = {}) => {
    if (expr[0] !== '(')
        return /[0-9]|-/.test(expr[0]) ? +expr : map[expr];

    map = Object.assign({}, map);
    const start = expr[1] === 'm' ? 6 : 5;
    const tokens = parse(expr.slice(start, expr.length - 1));

    if (expr.startsWith('(m')) return helper(tokens[0], map) * helper(tokens[1], map);
    if (expr.startsWith('(a')) return helper(tokens[0], map) + helper(tokens[1], map);

    for (let i = 0; i < tokens.length - 2; i += 2)
        map[tokens[i]] = helper(tokens[i + 1], map);

    return helper(tokens.at(-1), map);
}

const parse = expr => {
    const tokens = [];
    let [builder, par] = ['', 0];

    for (let ch of expr) {
        if (ch === '(') par++;
        if (ch === ')') par--;
        if (!par && ch === ' ') {
            tokens.push(builder);
            builder = '';
        }
        else builder += ch;
    }

    return builder ? [...tokens, builder] : tokens;
}
Parse Lisp Expression