<?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>expression Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/expression/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/expression/</link>
	<description></description>
	<lastBuildDate>Sun, 10 Apr 2022 06:22: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>expression Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/expression/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2232. Minimize Result by Adding Parentheses to Expression</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-2232-minimize-result-by-adding-parentheses-to-expression/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-2232-minimize-result-by-adding-parentheses-to-expression/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 10 Apr 2022 06:20:27 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[parentheses]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9636</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;string&#160;expression&#160;of the form&#160;"&#60;num1&#62;+&#60;num2&#62;"&#160;where&#160;&#60;num1&#62;&#160;and&#160;&#60;num2&#62;&#160;represent positive integers. Add a pair of parentheses to&#160;expression&#160;such that after the addition of parentheses,&#160;expression&#160;is a&#160;valid&#160;mathematical expression and evaluates to&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-2232-minimize-result-by-adding-parentheses-to-expression/">花花酱 LeetCode 2232. Minimize Result by Adding Parentheses to 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>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;string&nbsp;<code>expression</code>&nbsp;of the form&nbsp;<code>"&lt;num1&gt;+&lt;num2&gt;"</code>&nbsp;where&nbsp;<code>&lt;num1&gt;</code>&nbsp;and&nbsp;<code>&lt;num2&gt;</code>&nbsp;represent positive integers.</p>



<p>Add a pair of parentheses to&nbsp;<code>expression</code>&nbsp;such that after the addition of parentheses,&nbsp;<code>expression</code>&nbsp;is a&nbsp;<strong>valid</strong>&nbsp;mathematical expression and evaluates to the&nbsp;<strong>smallest</strong>&nbsp;possible value. The left parenthesis&nbsp;<strong>must</strong>&nbsp;be added to the left of&nbsp;<code>'+'</code>&nbsp;and the right parenthesis&nbsp;<strong>must</strong>&nbsp;be added to the right of&nbsp;<code>'+'</code>.</p>



<p>Return&nbsp;<code>expression</code><em>&nbsp;after adding a pair of parentheses such that&nbsp;</em><code>expression</code><em>&nbsp;evaluates to the&nbsp;<strong>smallest</strong>&nbsp;possible value.</em>&nbsp;If there are multiple answers that yield the same result, return any of them.</p>



<p>The input has been generated such that the original value of&nbsp;<code>expression</code>, and the value of&nbsp;<code>expression</code>&nbsp;after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> expression = "247+38"
<strong>Output:</strong> "2(47+38)"
<strong>Explanation:</strong> The <code>expression</code> evaluates to 2 * (47 + 38) = 2 * 85 = 170.
Note that "2(4)7+38" is invalid because the right parenthesis must be to the right of the <code>'+'</code>.
It can be shown that 170 is the smallest possible value.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> expression = "12+34"
<strong>Output:</strong> "1(2+3)4"
<strong>Explanation:</strong> The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> expression = "999+999"
<strong>Output:</strong> "(999+999)"
<strong>Explanation:</strong> The <code>expression</code> evaluates to 999 + 999 = 1998.
</pre>



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



<ul><li><code>3 &lt;= expression.length &lt;= 10</code></li><li><code>expression</code>&nbsp;consists of digits from&nbsp;<code>'1'</code>&nbsp;to&nbsp;<code>'9'</code>&nbsp;and&nbsp;<code>'+'</code>.</li><li><code>expression</code>&nbsp;starts and ends with digits.</li><li><code>expression</code>&nbsp;contains exactly one&nbsp;<code>'+'</code>.</li><li>The original value of&nbsp;<code>expression</code>, and the value of&nbsp;<code>expression</code>&nbsp;after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.</li></ul>



<h2><strong>Solution: Brute Force</strong></h2>



<p>Try all possible positions to add parentheses and evaluate the new expression.</p>



<p>Time complexity: O(n<sup>2</sup>)<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:
  string minimizeResult(string expression) {
    const int n = expression.size();
    auto p = expression.find('+');
    int best = INT_MAX;
    string ans;
    for (int l = 0; l &lt; p; ++l)
      for (int r = p + 2; r &lt; n + 1; ++r) {
        const int m1 = l ? stoi(expression.substr(0, l)) : 1;
        const int m2 = (r &lt; n) ? stoi(expression.substr(r)) : 1;
        const int n1 = stoi(expression.substr(l, p));
        const int n2 = stoi(expression.substr(p + 1, r - p - 1));
        const int cur = m1 * (n1 + n2) * m2;
        if (cur &lt; best) {
          best = cur;
          ans = expression;
          ans.insert(l, &quot;(&quot;);
          ans.insert(r + 1, &quot;)&quot;);
        }
      }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-2232-minimize-result-by-adding-parentheses-to-expression/">花花酱 LeetCode 2232. Minimize Result by Adding Parentheses to 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/string/leetcode-2232-minimize-result-by-adding-parentheses-to-expression/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1896. Minimum Cost to Change the Final Value of Expression</title>
		<link>https://zxi.mytechroad.com/blog/recursion/leetcode-1896-minimum-cost-to-change-the-final-value-of-expression/</link>
					<comments>https://zxi.mytechroad.com/blog/recursion/leetcode-1896-minimum-cost-to-change-the-final-value-of-expression/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 10 Aug 2021 06:27:59 +0000</pubDate>
				<category><![CDATA[Recursion]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[recursion]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8558</guid>

					<description><![CDATA[<p>You are given a&#160;valid&#160;boolean expression as a string&#160;expression&#160;consisting of the characters&#160;'1','0','&#38;'&#160;(bitwise&#160;AND&#160;operator),'&#124;'&#160;(bitwise&#160;OR&#160;operator),'(', and&#160;')'. For example,&#160;"()1&#124;1"&#160;and&#160;"(1)&#38;()"&#160;are&#160;not valid&#160;while&#160;"1",&#160;"(((1))&#124;(0))", and&#160;"1&#124;(0&#38;(1))"&#160;are&#160;valid&#160;expressions. Return&#160;the&#160;minimum cost&#160;to change the final value of the expression.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-1896-minimum-cost-to-change-the-final-value-of-expression/">花花酱 LeetCode 1896. Minimum Cost to Change the Final Value of 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>You are given a&nbsp;<strong>valid</strong>&nbsp;boolean expression as a string&nbsp;<code>expression</code>&nbsp;consisting of the characters&nbsp;<code>'1'</code>,<code>'0'</code>,<code>'&amp;'</code>&nbsp;(bitwise&nbsp;<strong>AND</strong>&nbsp;operator),<code>'|'</code>&nbsp;(bitwise&nbsp;<strong>OR</strong>&nbsp;operator),<code>'('</code>, and&nbsp;<code>')'</code>.</p>



<ul><li>For example,&nbsp;<code>"()1|1"</code>&nbsp;and&nbsp;<code>"(1)&amp;()"</code>&nbsp;are&nbsp;<strong>not valid</strong>&nbsp;while&nbsp;<code>"1"</code>,&nbsp;<code>"(((1))|(0))"</code>, and&nbsp;<code>"1|(0&amp;(1))"</code>&nbsp;are&nbsp;<strong>valid</strong>&nbsp;expressions.</li></ul>



<p>Return<em>&nbsp;the&nbsp;<strong>minimum cost</strong>&nbsp;to change the final value of the expression</em>.</p>



<ul><li>For example, if&nbsp;<code>expression = "1|1|(0&amp;0)&amp;1"</code>, its&nbsp;<strong>value</strong>&nbsp;is&nbsp;<code>1|1|(0&amp;0)&amp;1 = 1|1|0&amp;1 = 1|0&amp;1 = 1&amp;1 = 1</code>. We want to apply operations so that the<strong>&nbsp;new</strong>&nbsp;expression evaluates to&nbsp;<code>0</code>.</li></ul>



<p>The&nbsp;<strong>cost</strong>&nbsp;of changing the final value of an expression is the&nbsp;<strong>number of operations</strong>&nbsp;performed on the expression. The types of&nbsp;<strong>operations</strong>&nbsp;are described as follows:</p>



<ul><li>Turn a&nbsp;<code>'1'</code>&nbsp;into a&nbsp;<code>'0'</code>.</li><li>Turn a&nbsp;<code>'0'</code>&nbsp;into a&nbsp;<code>'1'</code>.</li><li>Turn a&nbsp;<code>'&amp;'</code>&nbsp;into a&nbsp;<code>'|'</code>.</li><li>Turn a&nbsp;<code>'|'</code>&nbsp;into a&nbsp;<code>'&amp;'</code>.</li></ul>



<p><strong>Note:</strong>&nbsp;<code>'&amp;'</code>&nbsp;does&nbsp;<strong>not</strong>&nbsp;take precedence over&nbsp;<code>'|'</code>&nbsp;in the&nbsp;<strong>order of calculation</strong>. Evaluate parentheses&nbsp;<strong>first</strong>, then in&nbsp;<strong>left-to-right</strong>&nbsp;order.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> expression = "1&amp;(0|1)"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can turn "1&amp;(0<strong>|</strong>1)" into "1&amp;(0<strong>&amp;</strong>1)" by changing the '|' to a '&amp;' using 1 operation.
The new expression evaluates to 0. 
</pre>



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



<pre class="crayon-plain-tag">&lt;strong&gt;Input:&lt;/strong&gt; expression = &quot;(0&amp;amp;0)&amp;amp;(0&amp;amp;0&amp;amp;0)&quot;
&lt;strong&gt;Output:&lt;/strong&gt; 3
&lt;strong&gt;Explanation:&lt;/strong&gt; We can turn &quot;(0&lt;strong&gt;&amp;amp;0&lt;/strong&gt;)&lt;strong&gt;&lt;u&gt;&amp;amp;&lt;/u&gt;&lt;/strong&gt;(0&amp;amp;0&amp;amp;0)&quot; into &quot;(0&lt;strong&gt;|1&lt;/strong&gt;)&lt;strong&gt;|&lt;/strong&gt;(0&amp;amp;0&amp;amp;0)&quot; using 3 operations.
The new expression evaluates to 1.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> expression = "(0|(1|0&amp;1))"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can turn "(0|(<strong>1</strong>|0&amp;1))" into "(0|(<strong>0</strong>|0&amp;1))" using 1 operation.
The new expression evaluates to 0.</pre>



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



<ul><li><code>1 &lt;= expression.length &lt;= 10<sup>5</sup></code></li><li><code>expression</code>&nbsp;only contains&nbsp;<code>'1'</code>,<code>'0'</code>,<code>'&amp;'</code>,<code>'|'</code>,<code>'('</code>, and&nbsp;<code>')'</code></li><li>All parentheses&nbsp;are properly matched.</li><li>There will be no empty parentheses (i.e:&nbsp;<code>"()"</code>&nbsp;is not a substring of&nbsp;<code>expression</code>).</li></ul>



<h2><strong>Solution: DP, Recursion / Simulation w/ Stack</strong></h2>



<p>For each expression, stores the min cost to change value to 0 and 1.</p>



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



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

<pre class="crayon-plain-tag">class Solution {
public:
  int minOperationsToFlip(string expression) {
    stack&lt;array&lt;int, 3&gt;&gt; s;
    s.push({0, 0, 0});
    for (char e : expression) {
      if (e == '(')
        s.push({0, 0, 0});
      else if (e == '&amp;' || e == '|')
        s.top()[2] = e;
      else {        
        if (isdigit(e)) s.push({e != '0', e != '1', 0});
        auto [r0, r1, _] = s.top(); s.pop();
        auto [l0, l1, op] = s.top(); s.pop();
        if (op == '&amp;') {
          s.push({min(l0, r0),
                  min(l1 + r1, min(l1, r1) + 1),
                  0});
        } else if (op == '|') {
          s.push({min(l0 + r0, min(l0, r0) + 1),
                  min(l1, r1),
                  0});
        } else {
          s.push({r0, r1, 0});
        }
      }
    }
    return max(s.top()[0], s.top()[1]);
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-1896-minimum-cost-to-change-the-final-value-of-expression/">花花酱 LeetCode 1896. Minimum Cost to Change the Final Value of 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-1896-minimum-cost-to-change-the-final-value-of-expression/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 8. String to Integer (atoi)</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-8-string-to-integer-atoi/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-8-string-to-integer-atoi/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 12 Sep 2018 16:37:00 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[atoi]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[overflow]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3931</guid>

					<description><![CDATA[<p>Problem Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-8-string-to-integer-atoi/">花花酱 LeetCode 8. String to Integer (atoi)</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Implement <code>atoi</code> which converts a string to an integer.</p>
<p>The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.</p>
<p>The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.</p>
<p>If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.</p>
<p>If no valid conversion could be performed, a zero value is returned.</p>
<p><strong>Note:</strong></p>
<ul>
<li>Only the space character <code>' '</code> is considered as whitespace character.</li>
<li>Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2<sup>31</sup>,  2<sup>31 </sup>− 1]. If the numerical value is out of the range of representable values, INT_MAX (2<sup>31 </sup>− 1) or INT_MIN (−2<sup>31</sup>) is returned.</li>
</ul>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "42"
<strong>Output:</strong> 42
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "   -42"
<strong>Output:</strong> -42
<strong>Explanation:</strong> The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.
</pre>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "4193 with words"
<strong>Output:</strong> 4193
<strong>Explanation:</strong> Conversion stops at digit '3' as the next character is not a numerical digit.
</pre>
<p><strong>Example 4:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "words and 987"
<strong>Output:</strong> 0
<strong>Explanation:</strong> The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.</pre>
<p><strong>Example 5:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "-91283472332"
<strong>Output:</strong> -2147483648
<strong>Explanation:</strong> The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−2<sup>31</sup>) is returned.</pre>
<h1><strong>Solution: Simulation</strong></h1>
<p>You need to handle all corner cases in order to pass&#8230;</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int myAtoi(const string&amp; s) {
    long long ans = 0;
    int neg = 0;
    int pos = 0;
    bool p = false; // has '.'
    bool a = false; // has letters
    bool n = false; // has number
    for (int i = 0; i &lt; s.length(); ++i) {      
      if (s[i] == ' ') { if (n || neg || pos) break; }
      else if (s[i] == '-') { if (n) break; else neg++; }
      else if (s[i] == '+') { if (n) break; else pos++; }
      else if (s[i] == '.') p = true;
      else if (s[i] &gt;= '0' &amp;&amp; s[i] &lt;= '9' &amp;&amp; !p &amp;&amp; !a) {
        ans = ans * 10 + (s[i] - '0');
        n = true;
      } else {
        a = true;
      }
      if (ans / 10 &gt; INT_MAX) break; // ans can be &gt; 64 bit
    }

    if (neg) ans = -ans;

    if (ans &gt; INT_MAX) ans = INT_MAX;
    if (ans &lt; INT_MIN) ans = INT_MIN;

    if (pos + neg &gt; 1) ans = 0;

    return ans;
  }
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-8-string-to-integer-atoi/">花花酱 LeetCode 8. String to Integer (atoi)</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/simulation/leetcode-8-string-to-integer-atoi/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 282. Expression Add Operators</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-282-expression-add-operators/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-282-expression-add-operators/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 31 Jan 2018 07:00:21 +0000</pubDate>
				<category><![CDATA[Hard]]></category>
		<category><![CDATA[Search]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[hard]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1707</guid>

					<description><![CDATA[<p>题目大意：给你一个字符串，让你在数字之间加上+,-,*使得等式的值等于target。让你输出所有满足条件的表达式。 Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-282-expression-add-operators/">花花酱 LeetCode 282. Expression Add Operators</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/v05R1OIIg08?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：给你一个字符串，让你在数字之间加上+,-,*使得等式的值等于target。让你输出所有满足条件的表达式。</p>
<p>Given a string that contains only digits <code>0-9</code> and a target value, return all possibilities to add <b>binary</b> operators (not unary) <code>+</code>, <code>-</code>, or <code>*</code> between the digits so they evaluate to the target value.</p>
<p>Examples:</p><pre class="crayon-plain-tag">"123", 6 -&gt; ["1+2+3", "1*2*3"] 
"232", 8 -&gt; ["2*3+2", "2+3*2"]
"105", 5 -&gt; ["1*0+5","10-5"]
"00", 0 -&gt; ["0+0", "0-0", "0*0"]
"3456237490", 9191 -&gt; []</pre><p><strong>Slides:</strong></p>
<p><img class="alignnone size-full wp-image-1730" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/282-ep163-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/282-ep163-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/282-ep163-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/282-ep163-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><img class="alignnone size-full wp-image-1729" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/282-ep163-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/282-ep163-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/282-ep163-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/282-ep163-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<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></p>
<h1><strong>Solution 1: DFS</strong></h1>
<p>Time complexity: O(4^n)</p>
<p>Space complexity: O(n^2) -&gt; O(n)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 128 ms (&lt;79.97%)
class Solution {
public:
  vector&lt;string&gt; addOperators(string num, int target) {
    vector&lt;string&gt; ans;
    dfs(num, target, 0, "", 0, 0, &amp;ans);
    return ans;
  }
private:
  void dfs(const string&amp; num, const int target,  // input
           int pos, const string&amp; exp, long prev, long curr, // state
           vector&lt;string&gt;* ans) {  // output
    if (pos == num.length()) {
      if (curr == target) ans-&gt;push_back(exp);
      return;
    }
    
    for (int l = 1; l &lt;= num.size() - pos; ++l) {
      string t = num.substr(pos, l);    
      if (t[0] == '0' &amp;&amp; t.length() &gt; 1) break; // 0X...
      long n = std::stol(t);
      if (n &gt; INT_MAX) break;
      if (pos == 0) {
        dfs(num, target, l, t, n, n, ans);
        continue;
      }
      dfs(num, target, pos + l, exp + '+' + t, n, curr + n, ans);
      dfs(num, target, pos + l, exp + '-' + t, -n, curr - n, ans);
      dfs(num, target, pos + l, exp + '*' + t, prev * n, curr - prev + prev * n, ans);
    }    
  }
};</pre><p></div><h2 class="tabtitle">C++ / SC O(n)</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 13 ms (&lt; 99.14%)
class Solution {
public:
  vector&lt;string&gt; addOperators(string num, int target) {
    vector&lt;string&gt; ans;
    string exp(num.length() * 2, '\0');    
    dfs(num, target, 0, exp, 0, 0, 0, &amp;ans);
    return ans;
  }
private:
  void dfs(const string&amp; num, const int target,
           int pos, string&amp; exp, int len, long prev, long curr,
           vector&lt;string&gt;* ans) {    
    if (pos == num.length()) {      
      if (curr == target) ans-&gt;push_back(exp.substr(0, len));
      return;
    }
    
    long n = 0;
    int s = pos;
    int l = len;
    if (s != 0) ++len;    
    while (pos &lt; num.size()) {      
      n = n * 10 + (num[pos] - '0');
      if (num[s] == '0' &amp;&amp; pos - s &gt; 0) break; // 0X... invalid number
      if (n &gt; INT_MAX) break; // too long
      exp[len++] = num[pos++];
      if (s == 0) {
        dfs(num, target, pos, exp, len, n, n, ans);
        continue;
      }
      exp[l] = '+'; dfs(num, target, pos, exp, len, n, curr + n, ans);
      exp[l] = '-'; dfs(num, target, pos, exp, len, -n, curr - n, ans);
      exp[l] = '*'; dfs(num, target, pos, exp, len, prev * n, curr - prev + prev * n, ans);
    }
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 16 ms (&lt;99.17%)
class Solution {
  private List&lt;String&gt; ans;
  private char[] num;
  private char[] exp;
  private int target;
  
  public List&lt;String&gt; addOperators(String num, int target) {
    this.num = num.toCharArray();
    this.ans = new ArrayList&lt;&gt;();
    this.target = target;
    this.exp = new char[num.length() * 2];
    dfs(0, 0, 0, 0);
    return ans;
  }
  
  private void dfs(int pos, int len, long prev, long curr) {
    if (pos == num.length) {      
      if (curr == target)
        ans.add(new String(exp, 0, len));
      return;
    }
    
    int s = pos;
    int l = len;
    if (s != 0) ++len;
    
    long n = 0;
    while (pos &lt; num.length) {
      if (num[s] == '0' &amp;&amp; pos - s &gt; 0) break; // 0X...
      n = n * 10 + (int)(num[pos] - '0');      
      if (n &gt; Integer.MAX_VALUE) break; // too long
      exp[len++] = num[pos++]; // copy exp
      if (s == 0) {
        dfs(pos, len, n, n);
        continue;
      }
      exp[l] = '+'; dfs(pos, len, n, curr + n);
      exp[l] = '-'; dfs(pos, len, -n, curr - n);
      exp[l] = '*'; dfs(pos, len, prev * n, curr - prev + prev * n);
    }
  }
}</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-282-expression-add-operators/">花花酱 LeetCode 282. Expression Add Operators</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/searching/leetcode-282-expression-add-operators/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>
