dailylog 02-02-21
1 minute read
# FROM HERE https://leetcode.com/problems/longest-valid-parentheses/discuss/1030761/
# ... Python-Simple-Solutions-or-DP-and-Stack-One-pass
import unittest
def longestValidParentheses(my_string):
# INITIALIZES RESULT VAR
# INITIALIZES A STACK
result = 0
my_stack = []
# LOOPS THROUGH EACH PAREN IN STRING, BY ID NUMBER
# **** BY ID NUMBER ****
for idx in range(len(my_string)):
# If -- the character at the IDX we are iterating over is a "("
# Add the IDX to our stack
if my_string[idx] == '(':
my_stack.append(idx)
# If -- STACK exists, AND the last IDX in STACK
# corresponds to a '(' in STRING
# Remove the last IDX from the stack
# Create a LAST POSITION variable
# it becomes the last IDX in STACK (if stack exists)
# Create a CURRENT LENGTH variable
# It becomes the currend IDX minus Last Position
# Create a RESULT variable
# This simply takes the max between result and CURRENT LENGTH
elif my_stack and my_string[my_stack[-1]] == '(':
my_stack.pop()
lastPos = my_stack[-1] if my_stack else -1
curLen = idx - lastPos
result = max(result, curLen)
# Else -- Simply add the idx to the stack
else:
my_stack.append(idx)
return result
class Test(unittest.TestCase):
'''Test Cases'''
data = [
("(()", 2),
(")()())", 4),
("()(()", 2)
]
def test_paren_strings(self):
for [paren_string, expected] in self.data:
actual = longestValidParentheses(paren_string)
self.assertEqual(actual, expected)
unittest.main(argv=[''], verbosity=2, exit=False)