【LeetCode每天一題】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

思路

  在做這道題的時候比較有意思的是我想了兩種方法來解決,但是兩種方法都沒有能ac,第一種方法大概就是我從字符串s的第一個開始遍歷並申請一個tem變量來記錄為被匹配的字符串,當匹配到字符串之后重新將tem設置為"",最后遍歷完畢之后判斷tem是否為空從而得到是否可以滿足。這種思路缺陷就是我們能考慮有一種情況就是s="aaaaaaa", wordlidt=["aaaa", "aaa"],對於這個情況,她會每次都先匹配"aaa",這樣導致最后還剩下一個"a"。輸出False,所以不正確。
  在上一種方法的特殊情況下,我想到了使用遞歸,大概就是從頭開始遍歷遍歷,當遇到列表中存在的單詞時,我們將s以匹配的單詞去除作為參數進行遞歸,重新開始進行匹配。最后如果能匹配就可以得到True。但是這種解法最后因為超時也沒能AC。
  看了別人的答案之后發現原來還能使用動態規划來解決,大概思路就是申請一個比s字符串長1的輔助數組,初始化為False,第一個元素初始化True。最后我們設置兩層循環,第一層循環就是判斷輔助數組每一位是否能有列表中的單詞組合成,內層循環表示從0開始到第一層循環當前遍歷的位置,對每一種可能的字符串判斷是否在列表中。當最后遍歷完畢之后,輔助數組最后一個元素就是結果。
圖解思路

解決代碼

 
        
 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)    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM