<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>parser Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/parser/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/parser/</link>
	<description></description>
	<lastBuildDate>Sun, 06 Dec 2020 05:13:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>parser Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/parser/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1678. Goal Parser Interpretation</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1678-goal-parser-interpretation/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1678-goal-parser-interpretation/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 06 Dec 2020 05:13:07 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[parser]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7765</guid>

					<description><![CDATA[<p>You own a&#160;Goal Parser&#160;that can interpret a string&#160;command. The&#160;command&#160;consists of an alphabet of&#160;"G",&#160;"()"&#160;and/or&#160;"(al)"&#160;in some order. The Goal Parser will interpret&#160;"G"&#160;as the string&#160;"G",&#160;"()"&#160;as the string&#160;"o", and&#160;"(al)"&#160;as&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1678-goal-parser-interpretation/">花花酱 LeetCode 1678. Goal Parser Interpretation</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You own a&nbsp;<strong>Goal Parser</strong>&nbsp;that can interpret a string&nbsp;<code>command</code>. The&nbsp;<code>command</code>&nbsp;consists of an alphabet of&nbsp;<code>"G"</code>,&nbsp;<code>"()"</code>&nbsp;and/or&nbsp;<code>"(al)"</code>&nbsp;in some order. The Goal Parser will interpret&nbsp;<code>"G"</code>&nbsp;as the string&nbsp;<code>"G"</code>,&nbsp;<code>"()"</code>&nbsp;as the string&nbsp;<code>"o"</code>, and&nbsp;<code>"(al)"</code>&nbsp;as the string&nbsp;<code>"al"</code>. The interpreted strings are then concatenated in the original order.</p>



<p>Given the string&nbsp;<code>command</code>, return&nbsp;<em>the&nbsp;<strong>Goal Parser</strong>&#8216;s interpretation of&nbsp;</em><code>command</code>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> command = "G()(al)"
<strong>Output:</strong> "Goal"
<strong>Explanation:</strong>&nbsp;The Goal Parser interprets the command as follows:
G -&gt; G
() -&gt; o
(al) -&gt; al
The final concatenated result is "Goal".
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> command = "G()()()()(al)"
<strong>Output:</strong> "Gooooal"
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> command = "(al)G(al)()()G"
<strong>Output:</strong> "alGalooG"
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= command.length &lt;= 100</code></li><li><code>command</code>&nbsp;consists of&nbsp;<code>"G"</code>,&nbsp;<code>"()"</code>, and/or&nbsp;<code>"(al)"</code>&nbsp;in some order.</li></ul>



<h2><strong>Solution: String</strong></h2>



<p>If we encounter &#8216;(&#8216; check the next character to determine whether it&#8217;s &#8216;()&#8217; or &#8216;(al&#8217;)</p>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class Solution {
public:
  string interpret(string command) {
    string ans;
    for (int i = 0; i &lt; command.size(); ++i) {
      if (command[i] == 'G') ans += &quot;G&quot;;
      else if (command[i] == '(') {
        if (command[i + 1] == ')') ans += &quot;o&quot;;
        else ans += &quot;al&quot;;
      }
    }
    return ans;
  }
};</pre>

</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class Solution:
  def interpret(self, command: str) -&gt; str:
    ans = []
    for i, c in enumerate(command):
      if c == 'G': ans.append('G')
      elif c == '(':
        ans.append('o' if command[i + 1] == ')' else 'al')
    return ''.join(ans)</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1678-goal-parser-interpretation/">花花酱 LeetCode 1678. Goal Parser Interpretation</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-1678-goal-parser-interpretation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1106. Parsing A Boolean Expression</title>
		<link>https://zxi.mytechroad.com/blog/recursion/leetcode-1106-parsing-a-boolean-expression/</link>
					<comments>https://zxi.mytechroad.com/blog/recursion/leetcode-1106-parsing-a-boolean-expression/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 01 Jul 2019 06:32:46 +0000</pubDate>
				<category><![CDATA[Recursion]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[parser]]></category>
		<category><![CDATA[recursion]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5272</guid>

					<description><![CDATA[<p>Return the result of evaluating a given boolean&#160;expression, represented as a string. An expression can either be: "t", evaluating to&#160;True; "f", evaluating to&#160;False; "!(expr)", evaluating&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-1106-parsing-a-boolean-expression/">花花酱 LeetCode 1106. Parsing A Boolean Expression</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe width="500" height="375" src="https://www.youtube.com/embed/y2kFBqj_J08?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Return the result of evaluating a given boolean&nbsp;<code>expression</code>, represented as a string.</p>



<p>An expression can either be:</p>



<ul><li><code>"t"</code>, evaluating to&nbsp;<code>True</code>;</li><li><code>"f"</code>, evaluating to&nbsp;<code>False</code>;</li><li><code>"!(expr)"</code>, evaluating to the logical NOT of the inner expression&nbsp;<code>expr</code>;</li><li><code>"&amp;(expr1,expr2,...)"</code>, evaluating to the logical AND of 2 or more inner expressions&nbsp;<code>expr1, expr2, ...</code>;</li><li><code>"|(expr1,expr2,...)"</code>, evaluating to the logical OR of 2 or more inner expressions&nbsp;<code>expr1, expr2, ...</code></li></ul>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> expression = "!(f)"
<strong>Output:</strong> true
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> expression = "|(f,t)"
<strong>Output:</strong> true
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> expression = "&amp;(t,f)"
<strong>Output:</strong> false
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> expression = "|(&amp;(t,f,t),!(t))"
<strong>Output:</strong> false</pre>



<h2><strong>Solution: Recursion</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  bool parseBoolExpr(string expression) {
    int s = 0;
    return parse(expression, s);
  }
private:  
  bool parse(const string&amp;amp; exp, int&amp;amp; s) {
    char ch = exp[s++];    
    if (ch == 't') return true;      
    if (ch == 'f') return false;
    if (ch == '!') {
      bool ans = !parse(exp, ++s);
      ++s;
      return ans;
    } 
    bool is_and = (ch == '&amp;amp;');
    bool ans = is_and;
    ++s;
    while (true) {
      if (is_and) ans &amp;amp;= parse(exp, s);
      else ans |= parse(exp, s);
      if (exp[s++] == ')') break;
    }
    return ans;
  }
};</pre>

</div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class Solution {
  private int s;
  private char[] exp;
  public boolean parseBoolExpr(String expression) {
    exp = expression.toCharArray();
    s = 0;
    return parse() == 1;
  }
      
  private int parse() {
    char ch = exp[s++];
    if (ch == 't') return 1;
    if (ch == 'f') return 0;
    if (ch == '!') {
      ++s;
      int ans = 1 - parse();
      ++s;
      return ans;
    }
    boolean is_and = (ch == '&amp;');
    int ans = is_and ? 1 : 0;
    ++s;
    while (true) {
      if (is_and) ans &amp;= parse();
      else ans |= parse();
      if (exp[s++] == ')') break;
    }
    return ans;
  }
}</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-1106-parsing-a-boolean-expression/">花花酱 LeetCode 1106. Parsing A Boolean Expression</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/recursion/leetcode-1106-parsing-a-boolean-expression/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 736. Parse Lisp Expression</title>
		<link>https://zxi.mytechroad.com/blog/recursion/leetcode-736-parse-lisp-expression/</link>
					<comments>https://zxi.mytechroad.com/blog/recursion/leetcode-736-parse-lisp-expression/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 01 Dec 2017 09:18:37 +0000</pubDate>
				<category><![CDATA[Recursion]]></category>
		<category><![CDATA[eval]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[lisp]]></category>
		<category><![CDATA[parser]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1052</guid>

					<description><![CDATA[<p>Problem: 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&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-736-parse-lisp-expression/">花花酱 LeetCode 736. Parse Lisp Expression</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/C75nVjzsT9g?feature=oembed" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>You are given a string <code>expression</code> representing a Lisp-like expression to return the integer value of.</p>
<p>The syntax for these expressions is given as follows.</p>
<ul>
<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>
<li>(An integer could be positive or negative.)</li>
<li>A let-expression takes the form <code>(let v1 e1 v2 e2 ... vn en expr)</code>, where <code>let</code> is always the string <code>"let"</code>, then there are 1 or more pairs of alternating variables and expressions, meaning that the first variable <code>v1</code>is assigned the value of the expression <code>e1</code>, the second variable <code>v2</code> is assigned the value of the expression <code>e2</code>, and so on <b>sequentially</b>; and then the value of this let-expression is the value of the expression <code>expr</code>.</li>
<li>An add-expression takes the form <code>(add e1 e2)</code> where <code>add</code> is always the string <code>"add"</code>, there are always two expressions <code>e1, e2</code>, and this expression evaluates to the addition of the evaluation of <code>e1</code> and the evaluation of <code>e2</code>.</li>
<li>A mult-expression takes the form <code>(mult e1 e2)</code> where <code>mult</code> is always the string <code>"mult"</code>, there are always two expressions <code>e1, e2</code>, and this expression evaluates to the multiplication of the evaluation of <code>e1</code> and the evaluation of <code>e2</code>.</li>
<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>
<li>Finally, there is the concept of scope. When an expression of a variable name is evaluated, <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>
</ul>
<p><b>Evaluation Examples:</b></p><pre class="crayon-plain-tag">Input: (add 1 2)
Output: 3

Input: (mult 3 (add 2 3))
Output: 15

Input: (let x 2 (mult x 5))
Output: 10

Input: (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.

Input: (let x 3 x 2 x)
Output: 2
Explanation: Assignment in let statements is processed sequentially.

Input: (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.

Input: (let x 2 (add (let x 3 (let x 4 x)) x))
Output: 6
Explanation: Even though (let x 4 x) has a deeper scope, it is outside the context
of the final x in the add-expression.  That final x will equal 2.

Input: (let a1 3 b2 (add a1 1) b2) 
Output 4
Explanation: Variable names can contain digits after the first character.</pre><p><b>Note:</b></p>
<ul>
<li>The given string <code>expression</code> is 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>
<li>The length of <code>expression</code> is at most 2000. (It is also non-empty, as that would not be a legal expression.)</li>
<li>The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.</li>
</ul>
<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 />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Idea:</strong></p>
<p>Recursive parsing</p>
<p>Time complexity: O(n^2) in worst case O(n) in practice</p>
<p>Space complexity: O(n)</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/736-ep119-1.png"><img 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="(max-width: 960px) 100vw, 960px" /></a></p>
<p>&nbsp;</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/736-ep119-2.png"><img 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="(max-width: 960px) 100vw, 960px" /></a></p>
<p>&nbsp;</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/736-ep119-3.png"><img 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="(max-width: 960px) 100vw, 960px" /></a></p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 3 ms
class Solution {
public:
    int evaluate(string expression) {        
        scopes_.clear();
        int pos = 0;
        return eval(expression, pos);
    }
private:
    int eval(const string&amp; s, int&amp; pos) {
        scopes_.push_front(unordered_map&lt;string, int&gt;());
        int value = 0; // The return value of current expr        
        if (s[pos] == '(') ++pos;

        // command, variable or number
        const string token = getToken(s, pos);

        if (token == "add") {
            int v1 = eval(s, ++pos);
            int v2 = eval(s, ++pos);
            value = v1 + v2;
        } else if (token == "mult") {
            int v1 = eval(s, ++pos);
            int v2 = eval(s, ++pos);
            value = v1 * v2;
        } else if (token == "let") {
            string var;
            // expecting " var1 exp1 var2 exp2 ... last_expr)"
            while (s[pos] != ')') {
                ++pos;
                // Must be last_expr
                if (s[pos] == '(') {
                    value = eval(s, ++pos);
                    break;
                }                
                // Get a token, could be "x" or "-12" for last_expr
                var = getToken(s, pos);                
                // End of let, var is last_expr
                if (s[pos] == ')') {
                    if (isalpha(var[0]))
                        value = getValue(var);
                    else
                        value = stoi(var);
                    break;
                }
                // x -12 -&gt; set x to -12 and store in the current scope and take it as the current return value
                value = scopes_.front()[var] = eval(s, ++pos);
            }
        } else if (isalpha(token[0])) {            
            value = getValue(token); // symbol
        } else {            
            value = std::stoi(token); // number
        }
        if (s[pos] == ')') ++pos;        
        scopes_.pop_front();        
        return value;
    }
    
    int getValue(const string&amp; symbol) {
        for (const auto&amp; scope : scopes_)        
            if (scope.count(symbol)) return scope.at(symbol);
        return 0;
    }
    
    // Get a token from current pos.
    // "let x" -&gt; "let"
    // "-12 (add x y)" -&gt; "-12"
    string getToken(const string&amp; s, int&amp; pos) {        
        string token;
        while (pos &lt; s.length()) {            
            if (s[pos] == ')' || s[pos] == ' ') break;
            token += s[pos++];
        }
        return token;
    }
    
    deque&lt;unordered_map&lt;string, int&gt;&gt; scopes_; 
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-736-parse-lisp-expression/">花花酱 LeetCode 736. Parse Lisp Expression</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/recursion/leetcode-736-parse-lisp-expression/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
