题意:给定三个序列S1,S2,S3,对于S1,S2和S3比较,看S1、S2是否是和S3间隔排序的,譬如,S1 = “aabcc”,S2=”dbbca”,S3=”aadbbcbcac”,则是满足条件的。
思路:动规。维护数组dp[s1.length][s2.length]。先初始化dp数组,再进行判断。
代码:
package com.interLeaving;
public class InterLeaving {
public boolean isInterLeaving(String s1 ,String s2 , String s3) {
if(s1.length() + s2.length() != s3.length()) return false;
boolean[][] dp = new boolean[s1.length()+1][s2.length()+1];
for (int i = 1; i <= s1.length() && s1.charAt(i-1) == s3.charAt(i-1); i++)
dp[i][0] = true;
for (int j = 1; j <= s2.length() && s2.charAt(j-1) == s3.charAt(j-1); j++)
dp[0][j] = true;
for(int i = 1 ; i <= s1.length() ; i++){
for(int j = 1 ; j <= s2.length() ; j++){
char c = s3.charAt(i+j-1);
if(c == s1.charAt(i-1) && dp[i-1][j])
dp[i][j] = true;
if(c == s2.charAt(j-1) && dp[i][j-1])
dp[i][j] = true;
}
}
return dp[s1.length()][s2.length()];
}
public static void main(String[] args) {
String s1 = "aabcc";
String s2 = "dbbca";
String s3 = "aadbbcbcac";
System.out.println(new InterLeaving().isInterLeaving(s1, s2, s3));
}
}