{"id":1052,"date":"2017-12-01T01:18:37","date_gmt":"2017-12-01T09:18:37","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=1052"},"modified":"2018-04-19T08:38:42","modified_gmt":"2018-04-19T15:38:42","slug":"leetcode-736-parse-lisp-expression","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/recursion\/leetcode-736-parse-lisp-expression\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 736. Parse Lisp Expression"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 736. Parse Lisp Expression - \u5237\u9898\u627e\u5de5\u4f5c EP119\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/C75nVjzsT9g?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p><strong>Problem:<\/strong><\/p>\n<p>You are given a string\u00a0<code>expression<\/code>\u00a0representing a Lisp-like expression to return the integer value of.<\/p>\n<p>The syntax for these expressions is given as follows.<\/p>\n<ul>\n<li>An expression is either an integer, a let-expression, an add-expression, a mult-expression, or an assigned variable. Expressions always evaluate to a single integer.<\/li>\n<li>(An integer could be positive or negative.)<\/li>\n<li>A let-expression takes the form\u00a0<code>(let v1 e1 v2 e2 ... vn en expr)<\/code>, where\u00a0<code>let<\/code>\u00a0is always the string\u00a0<code>\"let\"<\/code>, then there are 1 or more pairs of alternating variables and expressions, meaning that the first variable\u00a0<code>v1<\/code>is assigned the value of the expression\u00a0<code>e1<\/code>, the second variable\u00a0<code>v2<\/code>\u00a0is assigned the value of the expression\u00a0<code>e2<\/code>, and so on\u00a0<b>sequentially<\/b>; and then the value of this let-expression is the value of the expression\u00a0<code>expr<\/code>.<\/li>\n<li>An add-expression takes the form\u00a0<code>(add e1 e2)<\/code>\u00a0where\u00a0<code>add<\/code>\u00a0is always the string\u00a0<code>\"add\"<\/code>, there are always two expressions\u00a0<code>e1, e2<\/code>, and this expression evaluates to the addition of the evaluation of\u00a0<code>e1<\/code>\u00a0and the evaluation of\u00a0<code>e2<\/code>.<\/li>\n<li>A mult-expression takes the form\u00a0<code>(mult e1 e2)<\/code>\u00a0where\u00a0<code>mult<\/code>\u00a0is always the string\u00a0<code>\"mult\"<\/code>, there are always two expressions\u00a0<code>e1, e2<\/code>, and this expression evaluates to the multiplication of the evaluation of\u00a0<code>e1<\/code>\u00a0and the evaluation of\u00a0<code>e2<\/code>.<\/li>\n<li>For the purposes of 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 &#8220;add&#8221;, &#8220;let&#8221;, or &#8220;mult&#8221; are protected and will never be used as variable names.<\/li>\n<li>Finally, there is the concept of scope. When an expression of a variable name is evaluated,\u00a0<b>within the context of that evaluation<\/b>, 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 scope.<\/li>\n<\/ul>\n<p><b>Evaluation Examples:<\/b><\/p>\n<pre class=\"\">Input: (add 1 2)\r\nOutput: 3\r\n\r\nInput: (mult 3 (add 2 3))\r\nOutput: 15\r\n\r\nInput: (let x 2 (mult x 5))\r\nOutput: 10\r\n\r\nInput: (let x 2 (mult x (let x 3 y 4 (add x y))))\r\nOutput: 14\r\nExplanation: In the expression (add x y), when checking for the value of the variable x,\r\nwe check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\r\nSince x = 3 is found first, the value of x is 3.\r\n\r\nInput: (let x 3 x 2 x)\r\nOutput: 2\r\nExplanation: Assignment in let statements is processed sequentially.\r\n\r\nInput: (let x 1 y 2 x (add x y) (add x y))\r\nOutput: 5\r\nExplanation: The first (add x y) evaluates as 3, and is assigned to x.\r\nThe second (add x y) evaluates as 3+2 = 5.\r\n\r\nInput: (let x 2 (add (let x 3 (let x 4 x)) x))\r\nOutput: 6\r\nExplanation: Even though (let x 4 x) has a deeper scope, it is outside the context\r\nof the final x in the add-expression.  That final x will equal 2.\r\n\r\nInput: (let a1 3 b2 (add a1 1) b2) \r\nOutput 4\r\nExplanation: Variable names can contain digits after the first character.<\/pre>\n<p><b>Note:<\/b><\/p>\n<ul>\n<li>The given string\u00a0<code>expression<\/code>\u00a0is well formatted: There are no leading or trailing spaces, there is only a single space separating different components of the string, and no space between adjacent parentheses. The expression is guaranteed to be legal and evaluate to an integer.<\/li>\n<li>The length of\u00a0<code>expression<\/code>\u00a0is at most 2000. (It is also non-empty, as that would not be a legal expression.)<\/li>\n<li>The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.<\/li>\n<\/ul>\n<p><ins class=\"adsbygoogle\" style=\"display: block; text-align: center;\" data-ad-layout=\"in-article\" data-ad-format=\"fluid\" data-ad-client=\"ca-pub-2404451723245401\" data-ad-slot=\"7983117522\"><\/ins><br \/>\n<script>\n     (adsbygoogle = window.adsbygoogle || []).push({});\n<\/script><\/p>\n<p><strong>Idea:<\/strong><\/p>\n<p>Recursive parsing<\/p>\n<p>Time complexity: O(n^2) in worst case O(n) in practice<\/p>\n<p>Space complexity: O(n)<\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/736-ep119-1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1063\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/736-ep119-1.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/736-ep119-1.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/736-ep119-1-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/736-ep119-1-768x432.png 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/736-ep119-2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1062\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/736-ep119-2.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/736-ep119-2.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/736-ep119-2-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/736-ep119-2-768x432.png 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/736-ep119-3.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1061\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/736-ep119-3.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/736-ep119-3.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/736-ep119-3-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/736-ep119-3-768x432.png 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<pre class=\"lang:c++ decode:true\">\/\/ Author: Huahua\r\n\/\/ Runtime: 3 ms\r\nclass Solution {\r\npublic:\r\n    int evaluate(string expression) {        \r\n        scopes_.clear();\r\n        int pos = 0;\r\n        return eval(expression, pos);\r\n    }\r\nprivate:\r\n    int eval(const string&amp; s, int&amp; pos) {\r\n        scopes_.push_front(unordered_map&lt;string, int&gt;());\r\n        int value = 0; \/\/ The return value of current expr        \r\n        if (s[pos] == '(') ++pos;\r\n\r\n        \/\/ command, variable or number\r\n        const string token = getToken(s, pos);\r\n\r\n        if (token == \"add\") {\r\n            int v1 = eval(s, ++pos);\r\n            int v2 = eval(s, ++pos);\r\n            value = v1 + v2;\r\n        } else if (token == \"mult\") {\r\n            int v1 = eval(s, ++pos);\r\n            int v2 = eval(s, ++pos);\r\n            value = v1 * v2;\r\n        } else if (token == \"let\") {\r\n            string var;\r\n            \/\/ expecting \" var1 exp1 var2 exp2 ... last_expr)\"\r\n            while (s[pos] != ')') {\r\n                ++pos;\r\n                \/\/ Must be last_expr\r\n                if (s[pos] == '(') {\r\n                    value = eval(s, ++pos);\r\n                    break;\r\n                }                \r\n                \/\/ Get a token, could be \"x\" or \"-12\" for last_expr\r\n                var = getToken(s, pos);                \r\n                \/\/ End of let, var is last_expr\r\n                if (s[pos] == ')') {\r\n                    if (isalpha(var[0]))\r\n                        value = getValue(var);\r\n                    else\r\n                        value = stoi(var);\r\n                    break;\r\n                }\r\n                \/\/ x -12 -&gt; set x to -12 and store in the current scope and take it as the current return value\r\n                value = scopes_.front()[var] = eval(s, ++pos);\r\n            }\r\n        } else if (isalpha(token[0])) {            \r\n            value = getValue(token); \/\/ symbol\r\n        } else {            \r\n            value = std::stoi(token); \/\/ number\r\n        }\r\n        if (s[pos] == ')') ++pos;        \r\n        scopes_.pop_front();        \r\n        return value;\r\n    }\r\n    \r\n    int getValue(const string&amp; symbol) {\r\n        for (const auto&amp; scope : scopes_)        \r\n            if (scope.count(symbol)) return scope.at(symbol);\r\n        return 0;\r\n    }\r\n    \r\n    \/\/ Get a token from current pos.\r\n    \/\/ \"let x\" -&gt; \"let\"\r\n    \/\/ \"-12 (add x y)\" -&gt; \"-12\"\r\n    string getToken(const string&amp; s, int&amp; pos) {        \r\n        string token;\r\n        while (pos &lt; s.length()) {            \r\n            if (s[pos] == ')' || s[pos] == ' ') break;\r\n            token += s[pos++];\r\n        }\r\n        return token;\r\n    }\r\n    \r\n    deque&lt;unordered_map&lt;string, int&gt;&gt; scopes_; \r\n};<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Problem: You are given a string\u00a0expression\u00a0representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. An&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[153],"tags":[174,173,172,171],"class_list":["post-1052","post","type-post","status-publish","format-standard","hentry","category-recursion","tag-eval","tag-expression","tag-lisp","tag-parser","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1052","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=1052"}],"version-history":[{"count":11,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1052\/revisions"}],"predecessor-version":[{"id":2669,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1052\/revisions\/2669"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=1052"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=1052"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=1052"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}