-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 17.8 MB (…
…21.16%)
- Loading branch information
Showing
2 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
<p>A parentheses string is valid if and only if:</p> | ||
|
||
<ul> | ||
<li>It is the empty string,</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>You are given a parentheses string <code>s</code>. In one move, you can insert a parenthesis at any position of the string.</p> | ||
|
||
<ul> | ||
<li>For example, if <code>s = "()))"</code>, you can insert an opening parenthesis to be <code>"(<strong>(</strong>)))"</code> or a closing parenthesis to be <code>"())<strong>)</strong>)"</code>.</li> | ||
</ul> | ||
|
||
<p>Return <em>the minimum number of moves required to make </em><code>s</code><em> valid</em>.</p> | ||
|
||
<p> </p> | ||
<p><strong class="example">Example 1:</strong></p> | ||
|
||
<pre> | ||
<strong>Input:</strong> s = "())" | ||
<strong>Output:</strong> 1 | ||
</pre> | ||
|
||
<p><strong class="example">Example 2:</strong></p> | ||
|
||
<pre> | ||
<strong>Input:</strong> s = "(((" | ||
<strong>Output:</strong> 3 | ||
</pre> | ||
|
||
<p> </p> | ||
<p><strong>Constraints:</strong></p> | ||
|
||
<ul> | ||
<li><code>1 <= s.length <= 1000</code></li> | ||
<li><code>s[i]</code> is either <code>'('</code> or <code>')'</code>.</li> | ||
</ul> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
# Approach: Open Bracket Counter | ||
|
||
# Time: O(n) | ||
# Space: O(1) | ||
|
||
class Solution: | ||
def minAddToMakeValid(self, s: str) -> int: | ||
open_brackets = 0 | ||
min_adds_required = 0 | ||
|
||
for c in s: | ||
if c == '(': | ||
open_brackets += 1 | ||
else: | ||
if open_brackets > 0: | ||
open_brackets -= 1 | ||
else: | ||
min_adds_required += 1 | ||
|
||
return min_adds_required + open_brackets |