字符串最大公共子序列以及最大公共子串问题

最大公共子序列
import java.util.Random;
public class LCS {

public static void main(String[] args){

//设置字符串长度
int substringLength1 = 20;
int substringLength2 = 20; //具体大小可自行设置

// 随机生成字符串
String x = GetRandomStrings(substringLength1);
String y = GetRandomStrings(substringLength2);
// 构造二维数组记录子问题x[i]和y[i]的LCS的长度
int[][] opt = new int[substringLength1 + 1][substringLength2 + 1];

// 从后向前,动态规划计算所有子问题。也可从前到后。
for (int i = substringLength1 - 1; i >= 0; i--){
for (int j = substringLength2 - 1; j >= 0; j--){
if (x.charAt(i) == y.charAt(j))
opt[i][j] = opt[i + 1][j + 1] + 1;//状态转移方程
else
opt[i][j] = Math.max(opt[i + 1][j], opt[i][j + 1]);//状态转移方程
}
}
System.out.println("substring1:"+x);
System.out.println("substring2:"+y);
System.out.print("LCS:");

int i = 0, j = 0;
while (i < substringLength1 && j < substringLength2){
if (x.charAt(i) == y.charAt(j)){
System.out.print(x.charAt(i));
i++;
j++;
} else if (opt[i + 1][j] >= opt[i][j + 1])
i++;
else
j++;
}
}

//取得定长随机字符串
public static String GetRandomStrings(int length){
StringBuffer buffer = new StringBuffer("abcdefghijklmnopqrstuvwxyz");
StringBuffer sb = new StringBuffer();
Random r = new Random();
int range = buffer.length();
for (int i = 0; i < length; i++){
sb.append(buffer.charAt(r.nextInt(range)));
}
return sb.toString();
}
}

最大公共子串
public static void lcs2(){
String x="abcdepoi";
String y="bcdefpoi";
int substringLength1 = x.length();
int substringLength2 = y.length();
int opt[][]=new int [substringLength1+1][substringLength2+1];
for(int i=1;i<=substringLength1;i++)
for(int j=1;j<=substringLength2;j++)
{
if(x.charAt(i-1)==y.charAt(j-1))
opt[i][j]=opt[i-1][j-1]+1;//状态转移方程,
}
int max=opt[0][0];
int m=0,n=0;
for(int i=substringLength1;i>=1;i--)
for(int j=substringLength2;j>=1;j--){
if(opt[i][j]>max)
{
max=opt[i][j];
m=i;
n=j;
}
}
System.out.println("x = "+x);
System.out.println("y = "+y);
System.out.println("max = "+max);
StringBuffer sb=new StringBuffer();
for(int i=m,j=n;i>=1&&j>=1;i--,j--)
{
if(opt[i][j]>0)
sb.append(x.charAt(i-1));
}
String result=sb.toString();
for(int i=result.length()-1;i>=0;i--)
System.out.print(result.charAt(i));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值