[LeetCode one question every day] Word Break ()

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.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.

Example 1:

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
             Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

思路

  In solving the problem is more interesting when I think of two ways to solve, but the two approaches are not able to ac, the first method is probably my first traversing from a string s and apply for a tem variable to a string of record is matched, when re-tem matched string is set to "", after completion of the last traversed is determined whether the empty tem whereby whether meet. This flaw is the idea that we can consider a situation that is s = "aaaaaaa", wordlidt = [ "aaaa", "aaa"], for this case, she would always first matches "aaa", which leads finally left The next "a". Output False, it is not correct. 
  In exceptional circumstances on a way, I think the use of recursion, probably from the beginning to traverse traversed, when faced with a list of words that exist, we will s to match the words as an argument to remove recursively, re-start the match . Finally, if we can match you can get True. But this solution because the last time out failed to AC.
  After seeing others find the answer to the original can be solved using dynamic programming, probably the idea is to apply a long string array of aid than 1 s, initialized to False, the first element is initialized True. Finally, we set the two cycles, the first auxiliary layer cycle is determined whether there is an array for each word in the list to a combination, the inner loop represents from 0 to the first layer of the current loop traversed position, for each possible determining whether a character string in the list. When the last traverse is completed, the auxiliary array is the result of the last element.
Graphic ideas

Resolution code

 
 1 class Solution(object):
 2     def wordBreak(self, s, wordDict):
 3         """
 4         :type s: str
 5         :type wordDict: List[str]
 6         :rtype: bool
 7         """
 8    
 9         if not s:
10             return True
11         dp = [False] *(len(s)+1)    # 申请辅助数组
12         dp[0] = True                 # 第一个设置为True
13         for i in range(1, len(s)+1):     # 外层循环
14             for j in range(i):           # 内存循环
15                 if dp[j] and s[j:i] in wordDict:     # 判断条件
16                     dp[i] = True             
17                     break
18         return dp[-1]
附上递归解法(s字符串过长时会超时)
 1 class Solution(object):
 2     def wordBreak(self, s, wordDict):
 3         """
 4         :type s: str
 5         :type wordDict: List[str]
 6         :rtype: bool
 7         """
 8         
 9         if not s:
10             return True
11         res= []
12         self.Bfs(s, wordDict, res)    # 进行递归遍历
13         if not res:
14             return False
15         return True
16         
17         
18     def Bfs(self, s, wordDict, res):
19         if not s:     # 如果s为空表示能够匹配,
20             res.append(True)
21             return 
22         tem = ""
23         for i in range(len(s)):     # 从头开始遍历
24             tem += s[i]            # 记录未匹配的值
25             if tem in wordDict:     # 当匹配到后,我们进行将s进行切割,
26                 self.Bfs(s[i+1:], wordDict, res)    

Guess you like

Origin www.cnblogs.com/GoodRnne/p/10950784.html