LintCode 交叉字符串
LCS类型的题,状态定义类型为dp[i][j] (0~i,0~j)
状态说明
符号 | 说明 |
---|---|
dp[i][j] | s1的从0开始的i个字符、s2的从0开始的j个字符,能否交叉构成s3的从0开始的i+j个字符 |
i | 表示s1子串长度(从0开始的子串) |
j | 表示s2子串长度(从0开始的子串) |
状态转移
- 在(i,j+1)的状态下转移到(i+1,j+1)
bool select1 = dp[i][j + 1] && (s1[i] == s3[i + j + 1]); - 在(i+1,j)的状态下转移到(i+1,j+1)
bool select2 = dp[i + 1][j] && (s2[j] == s3[i + j + 1]);
c++ code
bool isInterleave(string s1, string s2, string s3) {
// write your code here
memset(dp, 0, sizeof(0));
if (s3.length() != s1.length() + s2.length())
return false;
if (s1.length() == 0)
return s2 == s3;
if (s2.length() == 0)
return s1 == s3;
dp[0][0] = true;
for (int i = 0; i < s1.size(); ++i)
{
dp[i + 1][0] = (s1[i] == s3[i]) && dp[i][0];
}
for (int i = 0; i < s2.size(); ++i)
{
dp[0][i + 1] = (s2[i] == s3[i]) && dp[0][i];
}
for(int i=0;i<s1.size();++i)
for(int j=0;j<s2.size();++j)
{
bool select1 = dp[i][j + 1] && (s1[i] == s3[i + j + 1]);
bool select2 = dp[i + 1][j] && (s2[j] == s3[i + j + 1]);
dp[i + 1][j + 1] = select1 || select2;
}
return dp[s1.size()][s2.size()];
}