【交叉字符串java版本】

左神yyds系列


【交叉字符串java版本】_第1张图片

package Code01;

/*
 * 交叉子串问题
 * 字符串1和字符串2的字符交叉排列组合出目标字符串,要求相对位置不变
 * */

public class Demo08 {
	
	public static boolean process(String str1, String str2, String target) {
		if(str1.length()+str2.length() != target.length()) {
			return false;
		}
		char[] ch1 = str1.toCharArray();
		char[] ch2 = str2.toCharArray();
		char[] targetCh = target.toCharArray();
		boolean[][] dp = new boolean[str1.length()+1][str2.length()+1];
		dp[0][0] = true;
		for(int i = 0; i < str1.length(); i++) {
			if(dp[0][i] && ch1[i] == targetCh[i]) {
				dp[0][i+1] = true;
			}
		}
		for(int i = 0; i < str2.length(); i++) {
			if(dp[i][0] && ch2[i] == targetCh[i]) {
				dp[i+1][0] = true;
			}
		}
		for(int i = 0; i < str1.length(); i++) {
			for(int j = 0; j < str2.length(); j++) {
				if((dp[i][j+1] && ch1[i] == targetCh[i+j+1]) || (dp[i+1][j] && ch2[j] == targetCh[i+j+1])) {
					dp[i+1][j+1] = true;
				}
			}
		}
		return dp[str1.length()][str2.length()];
	}
	
	public static void main(String[] args) {
		String str1 = "abca";
		String str2 = "acah";
		String target = "aacbcaa";
		System.out.println(process(str1, str2, target));
	}
}

你可能感兴趣的:(左神yyds系列,java,算法,动态规划)