题目描述
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.
样例1
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
样例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.
算法1
动态规划
-
f[i]代表前i个字符组成的子串是否满足被给定word组合的条件。
-
与楼上几种动态规划略有不同,思路是直接顺序地去求f[i]、f[i+1]、f[i+2]
-
内层循环是沿着当前的指针向前寻找与word长度相同的子串去判断是否匹配。
时间复杂度
O(mn)
C++ 代码
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
vector<bool> f(s.length()+1);
f[0]=1;
for(int i=1;i<=s.length();i++)
{
for(auto word:wordDict)
{
if(word.length()<=i)
{
string sub=s.substr(i-word.length(),word.length());
if(sub.compare(word)==0&&f[i-word.length()])
{
f[i]=1;
break;
}
}
}
}
return f[s.length()];
}
};