Advertisement
Iam_Sandeep

921. Minimum Add to Make Parentheses Valid

Jul 13th, 2022
789
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.66 KB | None | 0 0
  1. #method 1
  2. class Solution:
  3.     def minAddToMakeValid(self, s: str) -> int:
  4.         ans=0
  5.         op,cl=0,0
  6.         for i in s:
  7.             if i=='(':
  8.                 op+=1
  9.             else:
  10.                 cl+=1
  11.             if op<cl:
  12.                 ans+=1
  13.                 cl-=1
  14.         ans+=abs(cl-op)
  15.         return ans
  16. #method 2
  17. class Solution:
  18.     def minAddToMakeValid(self, s: str) -> int:
  19.         st=[]
  20.         for i in s:
  21.             if i=='(':
  22.                 st.append(i)
  23.             else:
  24.                 if st and st[-1]=='(':
  25.                     st.pop()
  26.                 else:
  27.                     st.append(i)
  28.         return len(st)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement