最长公共子序列java_JAVA最长公共子序列

题目描述

使用动态规划算法求两个序列的最长公共子序列,需构造一条最长公共子序列。

输入

每组输入包括两行,每行包括一个字符串。

输出

两个字符序列的一条最长公共子序列。(输入已确保最长公共子序列的唯一性)

样例输入 Copy

acdbxx

ccdxx

样例输出 Copy

cdxx

package lianxi5;

import java.util.Scanner;

/*

* 最长公共子序列

*/

public class Main18 {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

String str1=sc.nextLine();

String str2=sc.nextLine();

char st1[]=new char[str1.length()];

char st2[]=new char[str2.length()];

for(int i=0;i

st1[i]=str1.charAt(i);

}

for(int i=0;i

st2[i]=str2.charAt(i);

}

maxCommonChar(st1,st2);

}

public static void maxCommonChar(char [] a, char [] b){

int m = a.length;

int n = b.length;

int [][] len = new int[m + 1][n + 1];

int [][] flags = new int[m + 1][n + 1];

for(int i = 0; i <= m - 1; i++){

for(int j = 0; j <= n - 1; j++){

if(a[i] == b[j]){

len[i + 1][j + 1] = len[i][j] + 1;

flags[i + 1][j + 1] = 1;

}else if(len[i + 1][j] >= len[i][j + 1]){

len[i + 1][j + 1] = len[i + 1][j];

flags[i + 1][j + 1] = 2;

}else{

len[i + 1][j + 1] = len[i][j + 1];

flags[i + 1][j + 1] = 3;

}

}

}

int k = len[m][n];

char [] commonChars = new char[k];

int i = m, j = n;

for(;i > 0 && j > 0;){

if(flags[i][j]==1){

commonChars[k - 1] = a[i - 1];

k--;

i--;

j--;

}else if(flags[i][j] == 2){

j--;

}else{

i--;

}

}

for(int l = 0; l <= len[m][n] - 1; l++){

System.out.print(commonChars[l]);

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值