Description
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
分析
题目的意思是:判断一个字符串能否分割成若干个字典中的单词。
- dp[i] 表示源串的前i个字符可以满足分割,那么 dp[ j ] 满足分割的条件是存在k 使得 dp [k] && substr[k,j]在字典里。
C++
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
vector<bool> dp(s.size()+1,false);
dp[0]=true;
for(int i=0;i<s.length();i++){
for(int j=i;j<s.length()&&dp[i];j++){
if(find(wordDict.begin(),wordDict.end(),s.substr(i,j-i+1))!=wordDict.end()){
dp[j+1]=true;
}
}
}
return dp[s.length()];
}
};
Python
假设我们有一个字符串s = “leetcode”,和一个字典wordDict = “leet”, “code”]。我们想知道字符串s能否被拆分成字典中的单词。
我们创建一个布尔型数组dp,长度为len(s) + 1,即9。dp[i]表示字符串s的前i个字符能否被拆分成字典中的单词。
初始化dp[0] = true,表示空字符串可以被拆分(因为没有任何单词)。
然后我们开始遍历字符串s的所有子字符串。对于每个子字符串,我们尝试所有可能的拆分位置。
例如,当i = 4时,我们考虑字符串s的前4个字符,即"leet"。我们尝试所有可能的拆分位置:
当j = 0时,我们检查dp[0](true)和"leet"是否在字典中(是)。所以,dp[4] = true,表示"leet"可以被拆分成字典中的单词。
当j = 1、2、3时,我们发现dp[j]都是false,所以不需要检查剩下的子字符串。
然后,当i = 8时,我们考虑字符串s的前8个字符,即"leetcode"。我们尝试所有可能的拆分位置:
当j = 0、1、2、3时,我们发现dp[j]都是false,所以不需要检查剩下的子字符串。
当j = 4时,我们检查dp[4](true)和"code"是否在字典中(是)。所以,dp[8] = true,表示"leetcode"可以被拆分成字典中的单词。
最后,我们返回dp[-1],即dp[8],它表示整个字符串s能否被拆分。在这个例子中,dp[8] = true,所以"leetcode"可以被拆分成"leet"和"code"。
在这个例子中,我们拆分了两次,但是实际上,dp[i]表示的是字符串s的前i个字符能否被拆分,而不是拆分的次数。拆分的次数取决于具体的字符串和字典。
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
# if word[j:i] in wordDict and dp[j] is True, dp[i]=True
n = len(s)
dp = [False]*(n+1)
dp[0]=True
for i in range(n+1):
for j in range(i):
if dp[j] and s[j:i] in wordDict:
dp[i]=True
return dp[n]