29 交叉字符串
Posted jxkun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了29 交叉字符串相关的知识,希望对你有一定的参考价值。
public class Solution {
/**
* @param s1: A string
* @param s2: A string
* @param s3: A string
* @return: Determine whether s3 is formed by interleaving of s1 and s2
*/
public boolean isInterleave(String s1, String s2, String s3) {
// write your code here
if(s1 == null || s2 == null || s3 == null || s1.length() + s2.length() != s3.length()){
return false;
}
int n = s1.length(), m = s2.length(), nm = s3.length();
boolean[][] dp = new boolean[n + 1][m + 1];
dp[0][0] = true;
for(int i = 1; i <= n; i++){
if(s1.charAt(i-1) == s3.charAt(i - 1)){
dp[i][0] = dp[i-1][0];
}
}
for(int i = 1; i <= m; i++){
if(s2.charAt(i-1) == s3.charAt(i-1)){
dp[0][i] = dp[0][i-1];
}
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(s1.charAt(i-1) == s3.charAt(i+j - 1)){
dp[i][j] = dp[i-1][j];
}
if(dp[i][j]){
continue;
}
if(s2.charAt(j-1) == s3.charAt(i+j-1)){
dp[i][j] = dp[i][j-1];
}
}
}
return dp[n][m];
}
}
以上是关于29 交叉字符串的主要内容,如果未能解决你的问题,请参考以下文章