1. 程式人生 > 實用技巧 >LeetCode 139. Word Break (Medium)

LeetCode 139. Word Break (Medium)

Given anon-emptystringsand a dictionarywordDictcontaining a list ofnon-emptywords, determine ifscan 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
方法1: DFS - TLE 方法2: dp 1 dp[i] represent if s[:i] could be constructed using the wordDict 2 for j that is smaller then I, if we have dp[j] that is True and s[j:I] exists in wordDict, then we update dp[i] = True 3 initialize dp[i] = False dp[0] = True 4 final answer dp[n] time complexity: O(N^2) space complexity: O(N)
class
Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: if not s or len(s) == 0: return True wordSet = set(wordDict) n = len(s) dp = [False for _ in range(n+1)] dp[0] = True for i in range(1, n+1): for j in range(i): if dp[j] and s[j:i] in wordSet: dp[i] = True return dp[n]