-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest_valid_parantheses.py
More file actions
52 lines (43 loc) · 1.2 KB
/
Copy pathlongest_valid_parantheses.py
File metadata and controls
52 lines (43 loc) · 1.2 KB
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
44
45
46
47
48
49
50
51
52
'''
Problem Number: 32
Difficulty level: Hard
Link: https://leetcode.com/problems/longest-valid-parentheses/description/
Author: namratabilurkar
'''
'''
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
'''
class Solution:
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
'''
1. Have a stack with -1 pushed in it.
2. If the character is '(', push it in the stack.
3. If the character is ')', pop from the stack.
4. If the stack is not empty, then find the maxLen using the following:
maxLen = i - stack[len(stack)-1], else, push i in the stack.
5. Return the maxLen
'''
stack = []
stack.append(-1)
maxLen = 0
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
stack.pop()
if stack:
maxLen = max(maxLen, i - stack[len(stack) - 1])
else:
stack.append(i)
return maxLen