Advertisement
Iam_Sandeep

678. Valid Parenthesis String

Jul 18th, 2022
913
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.36 KB | None | 0 0
  1. '''
  2. Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.
  3.  
  4. The following rules define a valid string:
  5.  
  6. Any left parenthesis '(' must have a corresponding right parenthesis ')'.
  7. Any right parenthesis ')' must have a corresponding left parenthesis '('.
  8. Left parenthesis '(' must go before the corresponding right parenthesis ')'.
  9. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".
  10. Constraints:
  11. 1 <= s.length <= 100
  12. s[i] is '(', ')' or '*'.
  13. '''
  14. #Method 2:O(n)
  15. '''
  16. position of * is important . For e,g, (* is true but *( is False.Hence we shall keep two stacks and store the indices one
  17. for the stars and other for open braces.
  18. Now when ever we get open brace or * we append them to respective stack.
  19. Incase of ')' we shall pop open stack if not empty else we check if there is any * then we shall pop.
  20. If both stacks seems to be empty then this closing brace cant be matched.Hence return False.
  21. After iterating the string now check whether open is empty or not. If its not empty we need to find respective closing
  22. braces using the star stack. For a match to happend we should find a star whose index is greater than open brace index.
  23. Watch techdose vidoe if you dont understand
  24. '''
  25. class Solution:
  26.     def checkValidString(self, s: str) -> bool:
  27.         n=len(s)
  28.         star=[]
  29.         op=[]
  30.         for i in range(n):
  31.             if s[i]=='(':
  32.                 op.append(i)
  33.             elif s[i]=='*':
  34.                 star.append(i)
  35.             else:
  36.                 if op:
  37.                     op.pop()
  38.                 elif star:
  39.                     star.pop()
  40.                 else:
  41.                     return False
  42.         #print(op,star)
  43.         while op and star:
  44.             if op[-1]<star.pop():
  45.                 op.pop()
  46.         if op:return False
  47.         return True
  48.                
  49.  
  50. #Method 1:O(n**3) Dp
  51. class Solution:
  52.     def checkValidString(self, s: str) -> bool:
  53.         n=len(s)
  54.         @cache
  55.         def dfs(i,dif):
  56.             if i==n:return dif==0
  57.             if dif<0:return False
  58.             if s[i]=='(':
  59.                 return dfs(i+1,dif+1)
  60.             elif s[i]==')':
  61.                 return dfs(i+1,dif-1)
  62.             else:
  63.                 return dfs(i+1,dif+1) or dfs(i+1,dif-1) or dfs(i+1,dif)
  64.         return dfs(0,0)
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement