daily pastebin goal
63%
SHARE
TWEET

Untitled

a guest Sep 21st, 2018 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. """
  2. Description:
  3. Remove the minimum number of invalid parentheses in order to make the input string
  4. valid. Return all possible results. The input string may contain letters other than
  5. the parentheses ( and ).
  6.  
  7. Examples:
  8. Input: "()())()"
  9. Output: ["()()()", "(())()"]
  10.  
  11. Input: "(a)())()"
  12. Output: ["(a)()()", "(a())()"]
  13.  
  14. Input: ")("
  15. Output: [""]
  16. """
  17.  
  18. def removeInvalidParentheses2(s):
  19.     """
  20.     :type s: str
  21.     :rtype: List[str]
  22.     """
  23.     def remove(s, last_i, last_j, parens, result):
  24.         i, count = last_i, 0
  25.         while i < len(s):
  26.             if s[i] == parens[0]:
  27.                 count += 1
  28.             elif s[i] == parens[1]:
  29.                 count -= 1
  30.             if count >= 0:
  31.                 i += 1
  32.                 continue
  33.             j = last_j
  34.             while j <= i:
  35.                 if s[j] == parens[1] and (j == last_j or s[j-1] != s[j]):
  36.                     remove(s[:j] + s[j+1:], i, j, parens, result)
  37.                 j += 1
  38.             return
  39.         if parens[1] == ')':
  40.             remove(s[::-1], 0, 0, (')', '('), result)
  41.         else:
  42.             result.append(s[::-1])
  43.     result = []
  44.     remove(s, 0, 0, ('(', ')'), result)
  45.     return result
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top