-
Notifications
You must be signed in to change notification settings - Fork 0
/
longestValidParentheses.py
43 lines (37 loc) · 1.36 KB
/
longestValidParentheses.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import unittest
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
match = 0
stack = []
stack.append(-1)
for j in range(len(s)):
i = s[j]
if( i == '('):
stack.append(j)
elif i ==')':
stack.pop()
if len(stack) != 0:
match = max(match, j - stack[len(stack)-1])
else:
stack.append(j)
return match
class TestUM(unittest.TestCase):
def setUp(self):
self.s = Solution()
def testBaseCase(self):
self.assertEqual(self.s.longestValidParentheses("") , 0)
self.assertEqual(self.s.longestValidParentheses("(") , 0)
self.assertEqual(self.s.longestValidParentheses(")") , 0)
self.assertEqual(self.s.longestValidParentheses("((((") , 0)
self.assertEqual(self.s.longestValidParentheses("))))") , 0)
self.assertEqual(self.s.longestValidParentheses("><") , 0)
def testlongestValidParentheses(self):
self.assertEqual(self.s.longestValidParentheses("()") , 2)
self.assertEqual(self.s.longestValidParentheses("()()") , 4)
self.assertEqual(self.s.longestValidParentheses("(()()") , 4)
if __name__ == '__main__':
unittest.main()