Given three strings: s1, s2, s3, determine whether s3 is formed by the interleaving of s1 and s2. Have you met this question in a real interview? Yes Example For s1 = "aabcc", s2 = "dbbca" When s3 = "aadbbcbcac", return true. When s3 = "aadbbbaccc", return false. Challenge O(n2) time or better
动态规划重点在于找到:维护量,递推式。维护量通过递推式递推,最后往往能得到想要的结果
先说说维护量,res[i][j]表示用s1的前i个字符和s2的前j个字符能不能按照规则表示出s3的前i+j个字符,如此最后结果就是res[s1.length()][s2.length()],判断是否为真即可。接下来就是递推式了,假设知道res[i][j]之前的所有历史信息,我们怎么得到res[i][j]。可以看出,其实只有两种方式来递推,一种是选取s1的字符作为s3新加进来的字符,另一种是选s2的字符作为新进字符。而要看看能不能选取,就是判断s1(s2)的第i(j)个字符是否与s3的i+j个字符相等。如果可以选取并且对应的res[i-1][j](res[i][j-1])也为真,就说明s3的i+j个字符可以被表示。这两种情况只要有一种成立,就说明res[i][j]为真,是一个或的关系。所以递推式可以表示成
res[i][j] = res[i-1][j]&&s1.charAt(i-1)==s3.charAt(i+j-1) || res[i][j-1]&&s2.charAt(j-1)==s3.charAt(i+j-1)
public boolean isInterleave(String s1, String s2, String s3) {
// write your code here
//state
int m = s1.length();
int n = s2.length();
int k = s3.length();
if (m + n != k) {
return false;
}
boolean[][] f = new boolean[m + 1][n + 1];
f[0][0] = true;
//initialize
for (int i = 1; i <= m; i++) {
if (s1.charAt(i - 1) == s3.charAt(i - 1) && f[i - 1][0]) {
f[i][0] = true;
}
}
for (int i = 1; i <= n; i++) {
if (s2.charAt(i - 1) == s3.charAt(i - 1) && f[0][i - 1]) {
f[0][i] = true;
}
}
//function
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s1.charAt(i - 1) == s3.charAt(i + j - 1) && f[i - 1][j] || s2.charAt(j - 1) == s3.charAt(i + j - 1) && f[i][j - 1]) {
f[i][j] = true;
}
}
}
return f[m][n];
}
dp 字符串考点: 当前字母是否用的上
1.题意转化到分情况后: 当前字母如果用上了与与前一个状态用题意怎么联系 用不上用题意怎么联系, 考察 多个状态和或最大值的递推: Distinct Subsequences
2. 题意转化到分情况上, 各个情况中哪个字母与当前字母匹配,当前状态由这个字母的上个状态怎么转化而来, 如本题.