<?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>parentheses Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/parentheses/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/parentheses/</link>
	<description></description>
	<lastBuildDate>Tue, 10 May 2022 15:25:14 +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>parentheses Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/parentheses/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2267. Check if There Is a Valid Parentheses String Path</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2267-check-if-there-is-a-valid-parentheses-string-path/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2267-check-if-there-is-a-valid-parentheses-string-path/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 10 May 2022 15:20:01 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[parentheses]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9734</guid>

					<description><![CDATA[<p>A parentheses string is a&#160;non-empty&#160;string consisting only of&#160;'('&#160;and&#160;')'. It is&#160;valid&#160;if&#160;any&#160;of the following conditions is&#160;true: It is&#160;(). It can be written as&#160;AB&#160;(A&#160;concatenated with&#160;B), where&#160;A&#160;and&#160;B&#160;are valid parentheses&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2267-check-if-there-is-a-valid-parentheses-string-path/">花花酱 LeetCode 2267. Check if There Is a Valid Parentheses String Path</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>A parentheses string is a&nbsp;<strong>non-empty</strong>&nbsp;string consisting only of&nbsp;<code>'('</code>&nbsp;and&nbsp;<code>')'</code>. It is&nbsp;<strong>valid</strong>&nbsp;if&nbsp;<strong>any</strong>&nbsp;of the following conditions is&nbsp;<strong>true</strong>:</p>



<ul><li>It is&nbsp;<code>()</code>.</li><li>It can be written as&nbsp;<code>AB</code>&nbsp;(<code>A</code>&nbsp;concatenated with&nbsp;<code>B</code>), where&nbsp;<code>A</code>&nbsp;and&nbsp;<code>B</code>&nbsp;are valid parentheses strings.</li><li>It can be written as&nbsp;<code>(A)</code>, where&nbsp;<code>A</code>&nbsp;is a valid parentheses string.</li></ul>



<p>You are given an&nbsp;<code>m x n</code>&nbsp;matrix of parentheses&nbsp;<code>grid</code>. A&nbsp;<strong>valid parentheses string path</strong>&nbsp;in the grid is a path satisfying&nbsp;<strong>all</strong>&nbsp;of the following conditions:</p>



<ul><li>The path starts from the upper left cell&nbsp;<code>(0, 0)</code>.</li><li>The path ends at the bottom-right cell&nbsp;<code>(m - 1, n - 1)</code>.</li><li>The path only ever moves&nbsp;<strong>down</strong>&nbsp;or&nbsp;<strong>right</strong>.</li><li>The resulting parentheses string formed by the path is&nbsp;<strong>valid</strong>.</li></ul>



<p>Return&nbsp;<code>true</code>&nbsp;<em>if there exists a&nbsp;<strong>valid parentheses string path</strong>&nbsp;in the grid.</em>&nbsp;Otherwise, return&nbsp;<code>false</code>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/03/15/example1drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [["(","(","("],[")","(",")"],["(","(",")"],["(","(",")"]]
<strong>Output:</strong> true
<strong>Explanation:</strong> The above diagram shows two possible paths that form valid parentheses strings.
The first path shown results in the valid parentheses string "()(())".
The second path shown results in the valid parentheses string "((()))".
Note that there may be other valid parentheses string paths.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/03/15/example2drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[")",")"],["(","("]]
<strong>Output:</strong> false
<strong>Explanation:</strong> The two possible paths form the parentheses strings "))(" and ")((". Since neither of them are valid parentheses strings, we return false.
</pre>



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



<ul><li><code>m == grid.length</code></li><li><code>n == grid[i].length</code></li><li><code>1 &lt;= m, n &lt;= 100</code></li><li><code>grid[i][j]</code>&nbsp;is either&nbsp;<code>'('</code>&nbsp;or&nbsp;<code>')'</code>.</li></ul>



<h2><strong>Solution: DP</strong></h2>



<p>Let dp(i, j, b) denote whether there is a path from (i,j) to (m-1, n-1) given b open parentheses.<br>if we are at (m &#8211; 1, n &#8211; 1) and b == 0 then we found a valid path.<br>dp(i, j, b) = dp(i + 1, j, b&#8217;) or dp(i, j + 1, b&#8217;) where b&#8217; = b + 1 if  grid[i][j] == &#8216;(&#8216; else -1</p>



<p>Time complexity: O(m*n*(m + n))<br><meta charset="utf-8">Space complexity: O(m*n*(m + n))</p>



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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def hasValidPath(self, grid: List[List[str]]) -&gt; bool:
    m, n = len(grid), len(grid[0])    
    
    @cache
    def dp(i: int, j: int, b: int) -&gt; bool:
      if b &lt; 0 or i == m or j == n: return False
      b += 1 if grid[i][j] == '(' else -1      
      if i == m - 1 and j == n - 1 and b == 0: return True      
      return dp(i + 1, j, b) or dp(i, j + 1, b)
    
    return dp(0, 0, 0)</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2267-check-if-there-is-a-valid-parentheses-string-path/">花花酱 LeetCode 2267. Check if There Is a Valid Parentheses String Path</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/dynamic-programming/leetcode-2267-check-if-there-is-a-valid-parentheses-string-path/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<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 1614. Maximum Nesting Depth of the Parentheses</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-1614-maximum-nesting-depth-of-the-parentheses/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-1614-maximum-nesting-depth-of-the-parentheses/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 11 Oct 2020 04:56:20 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[parentheses]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7474</guid>

					<description><![CDATA[<p>A string is a&#160;valid parentheses string&#160;(denoted&#160;VPS) if it meets one of the following: It is an empty string&#160;"", or a single character not equal to&#160;"("&#160;or&#160;")",&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1614-maximum-nesting-depth-of-the-parentheses/">花花酱 LeetCode 1614. Maximum Nesting Depth of the Parentheses</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>A string is a&nbsp;<strong>valid parentheses string</strong>&nbsp;(denoted&nbsp;<strong>VPS</strong>) if it meets one of the following:</p>



<ul><li>It is an empty string&nbsp;<code>""</code>, or a single character not equal to&nbsp;<code>"("</code>&nbsp;or&nbsp;<code>")"</code>,</li><li>It can be written as&nbsp;<code>AB</code>&nbsp;(<code>A</code>&nbsp;concatenated with&nbsp;<code>B</code>), where&nbsp;<code>A</code>&nbsp;and&nbsp;<code>B</code>&nbsp;are&nbsp;<strong>VPS</strong>&#8216;s, or</li><li>It can be written as&nbsp;<code>(A)</code>, where&nbsp;<code>A</code>&nbsp;is a&nbsp;<strong>VPS</strong>.</li></ul>



<p>We can similarly define the&nbsp;<strong>nesting depth</strong>&nbsp;<code>depth(S)</code>&nbsp;of any VPS&nbsp;<code>S</code>&nbsp;as follows:</p>



<ul><li><code>depth("") = 0</code></li><li><code>depth(A + B) = max(depth(A), depth(B))</code>, where&nbsp;<code>A</code>&nbsp;and&nbsp;<code>B</code>&nbsp;are&nbsp;<strong>VPS</strong>&#8216;s</li><li><code>depth("(" + A + ")") = 1 + depth(A)</code>, where&nbsp;<code>A</code>&nbsp;is a&nbsp;<strong>VPS</strong>.</li></ul>



<p>For example,&nbsp;<code>""</code>,&nbsp;<code>"()()"</code>, and&nbsp;<code>"()(()())"</code>&nbsp;are&nbsp;<strong>VPS</strong>&#8216;s (with nesting depths 0, 1, and 2), and&nbsp;<code>")("</code>&nbsp;and&nbsp;<code>"(()"</code>&nbsp;are not&nbsp;<strong>VPS</strong>&#8216;s.</p>



<p>Given a&nbsp;<strong>VPS</strong>&nbsp;represented as string&nbsp;<code>s</code>, return&nbsp;<em>the&nbsp;<strong>nesting depth</strong>&nbsp;of&nbsp;</em><code>s</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(1+(2*3)+((8)/4))+1"
<strong>Output:</strong> 3
<strong>Explanation:</strong> Digit 8 is inside of 3 nested parentheses in the string.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(1)+((2))+(((3)))"
<strong>Output:</strong> 3
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "1+(2*3)/(2-1)"
<strong>Output:</strong> 1
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "1"
<strong>Output:</strong> 0
</pre>



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



<ul><li><code>1 &lt;= s.length &lt;= 100</code></li><li><code>s</code>&nbsp;consists of digits&nbsp;<code>0-9</code>&nbsp;and characters&nbsp;<code>'+'</code>,&nbsp;<code>'-'</code>,&nbsp;<code>'*'</code>,&nbsp;<code>'/'</code>,&nbsp;<code>'('</code>, and&nbsp;<code>')'</code>.</li><li>It is guaranteed that parentheses expression&nbsp;<code>s</code>&nbsp;is a&nbsp;<strong>VPS</strong>.</li></ul>



<h2><strong>Solution: Stack</strong></h2>



<p>We only need to deal with &#8216;(&#8216; and &#8216;)&#8217;</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">// Author: Huahua
class Solution {
public:
  int maxDepth(string s) {
    int ans = 0;
    int d = 0;
    for (char c : s) {
      if (c == '(') ans = max(ans, ++d);
      else if (c == ')') --d;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1614-maximum-nesting-depth-of-the-parentheses/">花花酱 LeetCode 1614. Maximum Nesting Depth of the Parentheses</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/stack/leetcode-1614-maximum-nesting-depth-of-the-parentheses/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1541. Minimum Insertions to Balance a Parentheses String</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1541-minimum-insertions-to-balance-a-parentheses-string/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1541-minimum-insertions-to-balance-a-parentheses-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 09 Aug 2020 17:15:43 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[parentheses]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7219</guid>

					<description><![CDATA[<p>Given a parentheses string&#160;s&#160;containing only the characters&#160;'('&#160;and&#160;')'. A parentheses string is&#160;balanced&#160;if: Any left parenthesis&#160;'('&#160;must have a corresponding two consecutive right parenthesis&#160;'))'. Left parenthesis&#160;'('&#160;must go before&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1541-minimum-insertions-to-balance-a-parentheses-string/">花花酱 LeetCode 1541. Minimum Insertions to Balance a Parentheses String</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>Given a parentheses string&nbsp;<code>s</code>&nbsp;containing only the characters&nbsp;<code>'('</code>&nbsp;and&nbsp;<code>')'</code>. A parentheses string is&nbsp;<strong>balanced</strong>&nbsp;if:</p>



<ul><li>Any left parenthesis&nbsp;<code>'('</code>&nbsp;must have a corresponding two consecutive right parenthesis&nbsp;<code>'))'</code>.</li><li>Left parenthesis&nbsp;<code>'('</code>&nbsp;must go before the corresponding two&nbsp;consecutive right parenthesis&nbsp;<code>'))'</code>.</li></ul>



<p>For example,&nbsp;<code>"())"</code>,&nbsp;<code>"())(())))"</code>&nbsp;and&nbsp;<code>"(())())))"</code>&nbsp;are&nbsp;balanced,&nbsp;<code>")()"</code>,&nbsp;<code>"()))"</code>&nbsp;and&nbsp;<code>"(()))"</code>&nbsp;are not balanced.</p>



<p>You can insert the characters &#8216;(&#8216; and &#8216;)&#8217; at any position of the string to balance it if needed.</p>



<p>Return&nbsp;<em>the minimum number of insertions</em>&nbsp;needed to make&nbsp;<code>s</code>&nbsp;balanced.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(()))"
<strong>Output:</strong> 1
<strong>Explanation:</strong> The second '(' has two matching '))', but the first '(' has only ')' matching. We need to to add one more ')' at the end of the string to be "(())))" which is balanced.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "())"
<strong>Output:</strong> 0
<strong>Explanation:</strong> The string is already balanced.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "))())("
<strong>Output:</strong> 3
<strong>Explanation:</strong> Add '(' to match the first '))', Add '))' to match the last '('.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(((((("
<strong>Output:</strong> 12
<strong>Explanation:</strong> Add 12 ')' to balance the string.
</pre>



<p><strong>Example 5:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = ")))))))"
<strong>Output:</strong> 5
<strong>Explanation:</strong> Add 4 '(' at the beginning of the string and one ')' at the end. The string becomes "(((())))))))".
</pre>



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



<ul><li><code>1 &lt;= s.length &lt;= 10^5</code></li><li><code>s</code>&nbsp;consists of&nbsp;<code>'('</code>&nbsp;and&nbsp;<code>')'</code>&nbsp;only.</li></ul>



<h2><strong>Solution: Counting</strong></h2>



<p>Count how many close parentheses we need.</p>



<ol><li>if s[i] is &#8216;)&#8217;, we decrease the counter.<ol><li>if counter becomes negative, means we need to insert &#8216;(&#8216;<ol><li>increase ans by 1, increase the counter by 2, we need one more &#8216;)&#8217;</li><li>&#8216;)&#8217; -> &#8216;()&#8217; </li></ol></li></ol></li><li>if s[i] is &#8216;(&#8216;<ol><li>if we have an odd counter, means there is a unbalanced &#8216;)&#8217; e.g. &#8216;(()(&#8216;, counter is 3<ol><li>need to insert &#8216;)&#8217;, decrease counter, increase ans</li><li>&#8216;(()(&#8216; -> &#8216;(<s>())</s>(&#8216;, counter = 2</li></ol></li><li>increase counter by 2, each &#8216;(&#8216; needs two &#8216;)&#8217;s. &#8216;(<s>())</s>(&#8216; -> counter = 4</li></ol></li><li>Once done, if counter is greater than zero, we need insert that much &#8216;)s&#8217;<ol><li>counter = 5, &#8216;((()&#8217; -> &#8216;((())))))&#8217;</li></ol></li></ol>



<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 minInsertions(string s) {
    int ans = 0;
    int close = 0; // # of ')' needed.    
    for (char c : s) {
      if (c == ')') {
        if (--close &lt; 0) {          
          // need to insert one '('
          // ')' -&gt; '()'
          ++ans;
          close += 2;
        }
      } else {
        if (close &amp; 1) {          
          // need to insert one ')'
          // case '(()(' -&gt; '(())('
          --close;
          ++ans;
        }
        close += 2; // need two ')'s
      }
    }
    return ans + close;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1541-minimum-insertions-to-balance-a-parentheses-string/">花花酱 LeetCode 1541. Minimum Insertions to Balance a Parentheses String</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-1541-minimum-insertions-to-balance-a-parentheses-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 1249. Minimum Remove to Make Valid Parentheses</title>
		<link>https://zxi.mytechroad.com/blog/string/1249-minimum-remove-to-make-valid-parentheses/</link>
					<comments>https://zxi.mytechroad.com/blog/string/1249-minimum-remove-to-make-valid-parentheses/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 09 Nov 2019 16:36:13 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[parentheses]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5809</guid>

					<description><![CDATA[<p>Given a string&#160;s&#160;of&#160;'('&#160;,&#160;')'&#160;and lowercase English characters.&#160; Your task is to remove the minimum number of parentheses (&#160;'('&#160;or&#160;')',&#160;in any positions ) so that the resulting&#160;parentheses string&#160;is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/1249-minimum-remove-to-make-valid-parentheses/">花花酱 1249. Minimum Remove to Make Valid Parentheses</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>Given a string&nbsp;s&nbsp;of&nbsp;<code>'('</code>&nbsp;,&nbsp;<code>')'</code>&nbsp;and lowercase English characters.&nbsp;</p>



<p>Your task is to remove the minimum number of parentheses (&nbsp;<code>'('</code>&nbsp;or&nbsp;<code>')'</code>,&nbsp;in any positions ) so that the resulting&nbsp;<em>parentheses string</em>&nbsp;is valid and return&nbsp;<strong>any</strong>&nbsp;valid string.</p>



<p>Formally, a&nbsp;<em>parentheses string</em>&nbsp;is valid if and only if:</p>



<ul><li>It is the empty string, contains only lowercase characters, or</li><li>It can be written as&nbsp;<code>AB</code>&nbsp;(<code>A</code>&nbsp;concatenated with&nbsp;<code>B</code>), where&nbsp;<code>A</code>&nbsp;and&nbsp;<code>B</code>&nbsp;are valid strings, or</li><li>It can be written as&nbsp;<code>(A)</code>, where&nbsp;<code>A</code>&nbsp;is a valid string.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "lee(t(c)o)de)"
<strong>Output:</strong> "lee(t(c)o)de"
<strong>Explanation:</strong> "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "a)b(c)d"
<strong>Output:</strong> "ab(c)d"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "))(("
<strong>Output:</strong> ""
<strong>Explanation:</strong> An empty string is also valid.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(a(b(c)d)"
<strong>Output:</strong> "a(b(c)d)"
</pre>



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



<ul><li><code>1 &lt;= s.length &lt;= 10^5</code></li><li><code>s[i]</code>&nbsp;is one&nbsp;of&nbsp;&nbsp;<code>'('</code>&nbsp;,&nbsp;<code>')'</code>&nbsp;and&nbsp;lowercase English letters<code>.</code></li></ul>



<h2><strong>Solution: Couting</strong></h2>



<p>Count how many &#8220;(&#8221; are open and how many &#8220;)&#8221; left.</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">// Author: Huahua
class Solution {
public:
  string minRemoveToMakeValid(string s) {    
    int close = count(begin(s), end(s), ')');    
    int open = 0;
    string ans;    
    
    for (char c : s) {
      if (c == '(') {
        if (open == close) continue;
        ++open;
      } else if (c == ')') {
        --close;
        if (open == 0) continue;
        --open;
      }
      ans += c;
    }    
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/1249-minimum-remove-to-make-valid-parentheses/">花花酱 1249. Minimum Remove to Make Valid Parentheses</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/1249-minimum-remove-to-make-valid-parentheses/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 921. Minimum Add to Make Parentheses Valid</title>
		<link>https://zxi.mytechroad.com/blog/uncategorized/leetcode-921-minimum-add-to-make-parentheses-valid/</link>
					<comments>https://zxi.mytechroad.com/blog/uncategorized/leetcode-921-minimum-add-to-make-parentheses-valid/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 14 Oct 2018 03:03:59 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[parentheses]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4183</guid>

					<description><![CDATA[<p>Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid. Formally,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/uncategorized/leetcode-921-minimum-add-to-make-parentheses-valid/">花花酱 LeetCode 921. Minimum Add to Make Parentheses Valid</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>Given a string <code>S</code> of <code>'('</code> and <code>')'</code> parentheses, we add the minimum number of parentheses ( <code>'('</code> or <code>')'</code>, and in any positions ) so that the resulting parentheses string is valid.</p>
<p>Formally, a parentheses string is valid if and only if:</p>
<ul>
<li>It is the empty string, or</li>
<li>It can be written as <code>AB</code> (<code>A</code> concatenated with <code>B</code>), where <code>A</code> and <code>B</code> are valid strings, or</li>
<li>It can be written as <code>(A)</code>, where <code>A</code> is a valid string.</li>
</ul>
<p>Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.</p>
<p>&nbsp;</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">"())"</span>
<strong>Output: </strong><span id="example-output-1">1</span>
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-2-1">"((("</span>
<strong>Output: </strong><span id="example-output-2">3</span>
</pre>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-3-1">"()"</span>
<strong>Output: </strong><span id="example-output-3">0</span>
</pre>
<p><strong>Example 4:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-4-1">"()))(("</span>
<strong>Output: </strong><span id="example-output-4">4</span></pre>
<p><strong>Note:</strong></p>
<ol>
<li><code>S.length &lt;= 1000</code></li>
<li><code>S</code> only consists of <code>'('</code> and <code>')'</code> characters.</li>
</ol>
<h1><strong>Solution: Counting</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</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 minAddToMakeValid(string S) {
    int l = 0;    
    int m = 0;
    for (char c : S) {
      if (c == '(') ++l;
      if (c == ')' &amp;&amp; l &gt; 0) {
        --l;
        ++m;
      }
    }
    return S.size() - m * 2;
  }
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/uncategorized/leetcode-921-minimum-add-to-make-parentheses-valid/">花花酱 LeetCode 921. Minimum Add to Make Parentheses Valid</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/uncategorized/leetcode-921-minimum-add-to-make-parentheses-valid/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 20. Valid Parentheses</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-20-valid-parentheses/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-20-valid-parentheses/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 02 Oct 2018 07:40:04 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[parentheses]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4110</guid>

					<description><![CDATA[<p>Problem Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-20-valid-parentheses/">花花酱 LeetCode 20. Valid Parentheses</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>Given a string containing just the characters <code>'('</code>, <code>')'</code>, <code>'{'</code>, <code>'}'</code>, <code>'['</code> and <code>']'</code>, determine if the input string is valid.</p>
<p>An input string is valid if:</p>
<ol>
<li>Open brackets must be closed by the same type of brackets.</li>
<li>Open brackets must be closed in the correct order.</li>
</ol>
<p>Note that an empty string is also considered valid.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "()"
<strong>Output:</strong> true
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "()[]{}"
<strong>Output:</strong> true
</pre>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "(]"
<strong>Output:</strong> false
</pre>
<p><strong>Example 4:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "([)]"
<strong>Output:</strong> false
</pre>
<p><strong>Example 5:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "{[]}"
<strong>Output:</strong> true
</pre>
<h1><strong>Solution: Stack</strong></h1>
<p>Using a stack to track the existing open parentheses, if the current one is a close parenthesis but does not match the top of the stack, return false, otherwise pop the stack. Check whether the stack is empty in the end.</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, 0 ms
class Solution {
public:
  bool isValid(string s) {
    map&lt;char, char&gt; p{{')', '('}, {']', '['}, {'}', '{'}};
    stack&lt;char&gt; st;    
    for (char c : s) {
      if (!p.count(c)) {
        st.push(c);
      } else {
        if (st.empty() || p[c] != st.top()) return false;        
        st.pop();
      }
    }
    return st.empty();
  }
};</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def isValid(self, s):
    p = {')' : '(', ']': '[', '}' : '{'}
    stack = []
    for c in s:
      if c not in p:
        stack.append(c)
      else:
        if not stack or stack[-1] != p[c]: return False
        stack.pop()
    return not stack</pre><p></div></div></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="https://zxi.mytechroad.com/blog/searching/leetcode-22-generate-parentheses/">花花酱 LeetCode 22. Generate Parentheses</a></li>
<li><a href="https://zxi.mytechroad.com/blog/searching/leetcode-301-remove-invalid-parentheses/">花花酱 LeetCode 301. Remove Invalid Parentheses</a></li>
<li><a href="https://zxi.mytechroad.com/blog/string/leetcode-856-score-of-parentheses/">花花酱 LeetCode 856. Score of Parentheses</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-20-valid-parentheses/">花花酱 LeetCode 20. Valid Parentheses</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/stack/leetcode-20-valid-parentheses/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
