【DP】用dp[i][j][k]表示当前走到 s[i], t[j] 时,不同字符个数为 k 时的方案数(长度),那么当s[i] == s[j]时,dp[i][j][0] = dp[i - 1][j - 1][0] + 1,dp[i][j][1] = dp[i - 1][j - 1][1];否则,dp[i][j][0] == 0, dp[i][j][1] = dp[i - 1][j - 1][0] + 1。然后把所有的dp[i][j][1]加起来就是答案了。
class Solution {
public int countSubstrings(String s, String t) {
int ans = 0;
int m = s.length(), n = t.length();
int[][][] dp = new int[m + 1][n + 1][2];
// dp[0][0][0] = 1;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[i][j][0] = dp[i - 1][j - 1][0] + 1;
dp[i][j][1] = dp[i - 1][j - 1][1];
ans += dp[i][j][1];
} else {
dp[i][j][1] = dp[i - 1][j - 1][0] + 1;
dp[i][j][0] = 0;
ans += dp[i][j][1];
}
}
}
return ans;
}
}