jinhuang1102

139. Word Break

Jan 31st, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.32 KB | None | 0 0
  1. """
  2. 139. Word Break
  3. Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
  4.  
  5. Input: s = "applepenapple", wordDict = ["apple", "pen"]
  6. Output: true
  7. Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
  8.             Note that you are allowed to reuse a dictionary word.
  9.  
  10. 思路:
  11. 这道题要我们找出并非一种可能的词语拆分,比如例子里面的 “applepenapple” 是由 apple * 2 + pen * 1 组成的。
  12. 所以第一个直接的想法就是backtrack,就从头开始brute force地去遍历每一个字母看看是不是在wordDict里面。如果在dict里面,那么就recursive地遍历后面的string。但是这种办法会产生OJ不让过,所以我们要用到一个memo的list去纪录每一步计算过的结果。
  13. 解法如下:
  14. 1)首先要把wordDict的list type 转换成 set type 这么做是因为我们要检查当前的string是否在wordDict中,x in list is O(n) 而 x in set is O(1)
  15. 2) 然后产生一个memo来记录我们计算过的位置 [-1] * len(str)
  16. 3) backtack 从index = 0 开始, 每一层递归中依次遍历到string的末尾, 如果当前遍历到的string在wordDict中,并且剩余的string也从recursive中返回为1那么就说明从index位开始到string的末尾,都能在wordDict中找到,然后修改memo[idx] = 1。如果在当前递归层中string遍历到末尾了都没有找到wordDict的值那就说明从index开始,不能再wordDict中找到,修改memo[idx] = 0
  17. """
  18.  
  19. class Solution(object):
  20.     def backtrack(self, s, idx, st, memo):
  21.         if idx == len(s):
  22.             return 1
  23.        
  24.         if memo[idx] != -1:
  25.             return memo[idx]
  26.        
  27.         for i in range( idx+1, len(s)+1 ):
  28.             if s[idx:i] in st and self.backtrack(s, i, st, memo):
  29.                 memo[idx] = 1
  30.                 return memo[idx]
  31.            
  32.         memo[idx] = 0
  33.         return memo[idx]
  34.    
  35.     def wordBreak(self, s, wordDict):
  36.         """
  37.        :type s: str
  38.        :type wordDict: List[str]
  39.        :rtype: bool
  40.        """
  41.         st = set(wordDict)
  42.         memo = [-1] * len(s)
  43.         res = self.backtrack(s, 0, st, memo)
  44.         return True if res is 1 else False
Add Comment
Please, Sign In to add comment