Problem 139. 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
Input: s = "leetcode", wordDict = ["leet", "code"] Output: true Explanation: Return true because "leetcode" can be segmented as "leet code".
-
解题思路
本题大意是:给定字符串 s 和字符串集 wordDict ,判断 s 能否拆分成若干个子串,使得每一个子串都与 wordDict 中的一个元素匹配。可用动态规划来解决。算法思路如下:
- 令 s 的长度为 len,令 dp 为一个含 len+1 个元素的布尔数组,并初始化为 false。其中 dp[i] 表示 s 中前 i 个字符能够拆分成若干个子串,使得每一个子串都与 wordDict 中的一个元素匹配;
- 令 dp[0] = true;
- 对 dp 进行遍历,dp[i] = true 的条件是:存在 j<i,使得 dp[j] = true,并且 s 中从下标 j 到 i 组成的字符串在 wordDict 能够匹配;
- 最后返回 dp[len] 即可。
- 代码实现
该算法的 C++ 和 Python 代码如下:
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int len = s.length();
vector<bool> dp(len+1, false);
dp[0] = true;
for(int i = 0; i <= len; ++i){
for(int j = 0; j < i; ++j)
if(dp[j] && find(wordDict.begin(), wordDict.end(), s.substr(j, i-j)) != wordDict.end())
dp[i] = true;
}
return dp[len];
}
};
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
size = len(s)
dp = [False for i in range(size+1)]
dp[0] = True
for i in range(size+1):
for j in range(i):
if(dp[j] and s[j:i] in wordDict):
dp[i] = True
return dp[size]