Advertisement
Iam_Sandeep

Longest Valid Parenthesis

Jul 8th, 2022
1,152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. '''
  2. Solution (Simulating with stack) :
  3.  
  4. We can use a stack to find the longest valid parentheses.
  5.  
  6. We will start by pushing -1 into the stack at first. This will denote index preceding to potential start of valid parentheses. It will be more clear later. Now will start iterating over s and we will have two cases -
  7.  
  8. s[i] == '(' - In this case, we will push the index into the stack (just as we do in valid parentheses check).
  9. s[i] == ')' - In this case, we will pop the index from the stack (again just as in parentheses check). Now, after popping, we need to do some simple checks which are main steps of this problem. Again, there will be following scenarios that may occur -
  10. 1)stack is not empty - If stack is not empty, then this may be our longest valid parentheses. We update the MAX_len as max(MAX_len, current index - stack.top()). Do notice, that our bottom of stack will always hold index preceding to a potential valid parentheses.
  11. 2)stack becomes empty - This will only happen when we have an extra ')' bracket. There may have been valid parentheses previously which have been updated and stored in MAX_len. But, since we now have an extra closing bracket any further extensions of previous valid parentheses is not possible. So, push the current index into stack, again which will denote that bottom of stack will hold the index preceding to a potential valid parentheses.
  12. '''
  13. # User function Template for Python3
  14.  
  15. class Solution:
  16.     def maxLength(self, s):
  17.         ans=0
  18.         st=[-1]
  19.         n=len(s)
  20.         for i in range(n):
  21.             if s[i]=='(':
  22.                 st.append(i)
  23.             else:
  24.                 st.pop()
  25.                 if not st:
  26.                     st.append(i)
  27.                 ans=max(ans,i-st[-1])
  28.         return ans
  29.  
  30.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement