Parse Lisp Expression LeetCode Solution

Last updated on October 9th, 2024 at 06:21 pm

Here, We see Parse Lisp Expression LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

String

Level of Question

Hard

Parse Lisp Expression LeetCode Solution

Parse Lisp Expression LeetCode Solution

Problem Statement

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 e1e2 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 e1e2 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.

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.

1. Parse Lisp Expression LeetCode Solution C++

class Solution {
public:
    int evaluate(string expression) {
        unordered_map<string, int> map;
        int idx = 0;
        return eval(expression, idx, map);
    }
    int eval(const string& exp, int& idx, const unordered_map<string, int>& map){
        int result;
        idx++;
        int end = exp.find(' ', idx);
        const string op = exp.substr(idx, end - idx);
        idx = end + 1;
        if(op == "add" || op == "mult"){
            const int v1 = parse_and_eval(exp, idx, map);
            const int v2 = parse_and_eval(exp, idx, map);
            result = op == "add" ? v1 + v2 : v1 * v2;
        }else{
            unordered_map<string, int> new_map = map;
            while(exp[idx] != '('){
                end = idx;
                while(exp[end] != ' ' && exp[end] != ')') ++end;
                if(exp[end] == ')') break;
                const string var = exp.substr(idx, end - idx);
                idx = end + 1;
                const int val = parse_and_eval(exp, idx, new_map);
                new_map[var] = val;
            }
            result = parse_and_eval(exp, idx, new_map);
        }
        idx++;
        return result;
    }
    int parse_and_eval(const string& exp, int& idx, const unordered_map<string, int>& map){
        int result;
        if(exp[idx] == '('){
            result = eval(exp, idx, map);
            if(exp[idx] == ' ') ++idx;
        }else{
            int end = idx;
            while(exp[end] != ' ' && exp[end] != ')') ++end;
            if(exp[idx] == '-' || (exp[idx] >= '0' && exp[idx] <= '9'))
                result = stoi(exp.substr(idx, end - idx));
            else
                result = map.at(exp.substr(idx, end - idx));
            idx = exp[end] == ' ' ? end + 1 : end;
        }
        return result;
    }
};

2. Parse Lisp Expression LeetCode Solution Java

class Solution {
    public int evaluate(String expression) {
        return eval(expression, new HashMap<>());
    }
    
    public int eval(String expression, Map<String, Integer> map){
        if (isNumber(expression)) return Integer.valueOf(expression);
        if (isVariable(expression)) return map.get(expression);
        
        int res = 0;
        List<String> list = parse(expression);
        if (list.get(0).equals("add")) res = eval(list.get(1), map) + eval(list.get(2), map);
        else if(list.get(0).equals("mult")) res = eval(list.get(1), map) * eval(list.get(2), map);
        else{
            Map<String, Integer> newMap = new HashMap<>();
            newMap.putAll(map);
            for (int i = 1;i<list.size()-1;i+=2)
                newMap.put(list.get(i), eval(list.get(i+1), newMap));
            res = eval(list.get(list.size()-1), newMap);
        }
        return res;
    }
    
    public boolean isNumber(String expr){
        char c = expr.charAt(0);
        return Character.isDigit(c) || c == '-';
    }

    public boolean isVariable(String expr){
        char c = expr.charAt(0);
        return Character.isLowerCase(c);
    }
    
    public List<String> parse(String expr){
        List<String> res = new ArrayList<>();
        expr = expr.substring(1, expr.length() - 1);
        
        int i = 0;
        while (i < expr.length()){
            int j = find(expr, i);
            res.add(expr.substring(i, j));
            i = j + 1;
        }
        return res;
    }
    
    public int find(String expr, int i){
        int index = i;
        if (expr.charAt(index) == '('){
            int count = 1;
            index++;
            while (index < expr.length() && count > 0){
				if (expr.charAt(index) == '(') count++;
                else if (expr.charAt(index) == ')') count--;
                index++;
            }
        }
        else 
			while (index < expr.length() && expr.charAt(index) != ' ') index++;
        return index;
    }
}

3. Parse Lisp Expression LeetCode Solution JavaScript

var evaluate = function(expression) {
    let map = {};
    return helper(expression, map);
};

var helper = function(expression, map) {
    if(isNumber(expression)) {
        return parseInt(expression);
    }else if(isVariable(expression)) {
        return map[expression];
    }
    
    let res = 0;
    let list = parse(expression);
   
    if(list[0] === 'add') {
        res = helper(list[1], map) + helper(list[2], map);
    } 
    else if(list[0] === 'mult') {
        res = helper(list[1], map) * helper(list[2], map);
    }
    else {
        let newMap = JSON.parse(JSON.stringify(map));
        for(let i = 1; i < list.length-1; i += 2) {
            newMap[list[i]] = helper(list[i+1], newMap); 
        }
        
        res = helper(list[list.length-1], newMap);
    }
    
    return res;
}

var isNumber = function(expression) {
    let c = expression.charAt(0);
    return c >= '0' && c <= '9' || c === '-';
}

var isVariable = function(expression) {
    let c = expression.charAt(0);
    return c >= 'a' && c <= 'z';
}

var parse = function(expression) {
    const array = [];
    expression = expression.substring(1, expression.length-1);
    let startIdx = 0;
    while(startIdx < expression.length) {
        let endIdx = next(expression, startIdx);
        array.push(expression.substring(startIdx, endIdx));
        
        startIdx = endIdx + 1;
    }
    
    return array;
}

var next = function(expression, startIdx) {
     let index = startIdx;
     
    if(expression.charAt(index) === '(') {
        let count = 1;
        index++;
        while(index < expression.length && count > 0) {
            if(expression.charAt(index) === '(') {
                count++;
            }else if(expression.charAt(index) === ')') {
                count--;
            }
            
            index++;
        }
    }else {
        while(index < expression.length && expression.charAt(index) !== ' ') {
            index++;
        }
    }
    return index;
}

4. Parse Lisp Expression LeetCode Solution Python

class Solution(object):
    def evaluate(self, expression):
        tokens = deque(expression.replace('(','( ').replace(')',' )').split())
        
        def eva(tokens,env):
            
            if tokens[0] != '(':
                if tokens[0][0] in '-1234567890':
                    return int(tokens.popleft())
                else:
                    return env[tokens.popleft()]
            else:
                tokens.popleft()
                if tokens[0] in ('add', 'mult'):
                    op = tokens.popleft()
                    a, b = eva(tokens, env), eva(tokens, env)
                    val = a + b if op == 'add' else a * b
                else:
                    tokens.popleft()
                    local = env.copy()
                    while tokens[0] != '(' and tokens[1] != ')':
                        var = tokens.popleft()
                        local[var] = eva(tokens, local)
                    val = eva(tokens, local)
                tokens.popleft()
                return val
            
        return eva(tokens,{})
Scroll to Top