1、Java AC
public class Solution { public boolean isInterleave(String s1, String s2, String s3) { int len1 = s1.length(); int len2 = s2.length(); int len = s3.length(); if(len1 + len2 != len){ return false; } int size = 1000; boolean dp[][] = new boolean[size][size]; dp[0][0] = true; for(int i = 1; i <= len1; i++){ dp[i][0] = dp[i-1][0] && (s1.charAt(i-1) == s3.charAt(i-1)); } for(int j = 1; j <= len2; j++){ dp[0][j] = dp[0][j-1] && (s2.charAt(j-1) == s3.charAt(j-1)); } for(int i = 1; i <= len1; i++){ for(int j = 1; j <= len2; j++){ dp[i][j] = (dp[i-1][j] && (s1.charAt(i-1) == s3.charAt(i+j-1))) || (dp[i][j-1] && (s2.charAt(j-1) == s3.charAt(i+j-1))); } } return dp[len1][len2]; } }2、C++ AC
#include <stdio.h> #include <string> #include <string.h> using namespace std; const int maxn = 300; char s1[maxn]; char s2[maxn]; char s3[maxn]; bool dp[maxn][maxn]; int i, j; bool isInterleave() { int len1 = strlen(s1); int len2 = strlen(s2); int len = strlen(s3); if (len1 + len2 != len) { return false; } dp[0][0] = true; for (i = 1; i <= len1; i++) { dp[i][0] = dp[i - 1][0] && (s1[i - 1] == s3[i - 1]); } for (j = 1; j <= len2; j++) { dp[0][j] = dp[0][j - 1] && (s2[j - 1] == s3[j - 1]); } for (i = 1; i <= len1; i++) { for (j = 1; j <= len2; j++) { dp[i][j] = (dp[i - 1][j] && (s1[i - 1] == s3[i + j - 1])) || (dp[i][j - 1] && (s2[j - 1] == s3[i + j - 1])); } } return dp[len1][len2]; } int main(){ while(scanf("%s",s1) != EOF){ scanf("%s",s2); scanf("%s",s3); bool flag = isInterleave(); printf("%s\n",flag == true ? "YES" : "NO"); } return 0; }