原题目:
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. You may assume the dictionary does not contain duplicate words.
For example, given
s = “leetcode”,
dict = [“leet”, “code”].
Return true because “leetcode” can be segmented as “leet code”
中文大意:
给定一个字符串向量作为字典,如[“leet”,”code”],以及一个待分割的字符串,如“leetcode”问有没有办法能够将这个字符串分割成多个连续子串,使得每个子串都在字典中,如”leetcode”在这种情况下可以分割成”leet” “code”,因此是可以的
题解:
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int len = s.size();
vector<vector<bool> >dp(len,vector<bool>(len,false));
for(int j = 0 ; j < len ;j++)
{
for(int i = j ; i >=0 ;i--)
{
bool currdp = false;
for(int k = i ;k<=j;k++)
{
string currstr = s.substr(k,j-k+1);
bool indict = find(wordDict.begin(), wordDict.end(), currstr )!=wordDict.end();
if(k==0)
currdp = currdp |indict;
else
currdp = currdp |(indict & dp[i][k-1]);
}
dp[i][j] = currdp;
}
}
return dp[0][len-1];
}
};
解析:
这道题目也出现在了《算法概论》的课后习题上。基本思路是通过二维数组(向量)来保存状态,记dp[i][j] = “在下标为i到j的子串中能够分割”,在这样的前提下,dp[i][j]的计算方式是:遍历每个在i到j的整数k,判断dp[i][k]&str(k,j)是否为真,只要存在一个k使得以上表达式为真,那dp[i][j]就等于TRUE。最终答案为dp[0][len-1],len为要求的字符串长度
整个算法下来空间复杂度为O(n^2),时间复杂度为O(n^3)