LeetCode 139. Word Break
原题链接在这里:https://leetcode.com/problems/word-break/
题目:
Given a string s
and a dictionary of strings wordDict
, return true
if s
can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
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
Constraints:
1 <= s.length <= 300
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 20
s
andwordDict[i]
consist of only lowercase English letters.- All the strings of
wordDict
are unique.
题解:
Let dp[i] denotes up to index i, s.substring(0,i) could break into words or not.
For all the j from 0 to i, if dp[j] is true, and s.substring(j,i) is in the dictionary, then dp[i] is true.
Time Complexity: O(s.length() ^ 3). since after Java 7, substring take O(n).
Space: O(s.length()).
AC Java:
1 class Solution { 2 public boolean wordBreak(String s, List<String> wordDict) { 3 if(s == null || s.length() == 0){ 4 return true; 5 } 6 7 Set<String> hs = new HashSet<>(wordDict); 8 int n = s.length(); 9 boolean [] dp = new boolean[n + 1]; 10 dp[0] = true; 11 for(int i = 0; i <= n; i++){ 12 for(int j = 0; j < i; j++){ 13 if(dp[j] && hs.contains(s.substring(j, i))){ 14 dp[i] = true; 15 break; 16 } 17 } 18 } 19 20 return dp[n]; 21 } 22 }
AC Python:
1 class Solution: 2 def wordBreak(self, s: str, wordDict: List[str]) -> bool: 3 dp = [False] * (len(s) + 1) 4 dp[0] = True 5 for i in range(len(s) + 1): 6 for j in range(i): 7 if dp[j] and s[j: i] in wordDict: 8 dp[i] = True 9 continue 10 11 return dp[-1]