最长公共子序列LCS-DP
来源:互联网 发布:安知玉如意好看吗 编辑:程序博客网 时间:2024/06/07 20:48
1.最长公共子序列
是指按顺序从两个字符串中获取的公共包含的元素集合。ABCDFDANNBMMFABF就是
动态规划
把一个大问题规划成好几个同样的子问题,然后分别求解。
public class LCSSTRING {/* 获取最长 公共子序列 */public class LCSSTRING { /* 获得状态转移数组 即得到一个数组用来存放字符串的信息实现DP */ public static int[][] lcs(String x,String y){ /* 数组前面要包含一个 0行 0 列 然后才接上字符串 的行和列 所以创建的时候要+1*/ int [][] c = new int[x.length()+1][y.length()+1]; /* 循环遍历两个字符串 */ for(int i = 1;i <= x.length();i++){ for(int j = 1;j <= y.length();j++){ System.out.println(" i:" + i + "j :" + j + "str : " + x.charAt(i-1) + " "+ y.charAt(j-1)); /* 字符串相等那么状态转移数组的值 为 左上角 +1 否则取上和左的最大值 */ if(x.charAt(i-1) == y.charAt(j-1)){ c[i][j] = c[i-1][j-1] + 1; }else if(c[i][j-1] >= c[i-1][j]){ c[i][j] = c[i][j-1]; }else if(c[i][j-1] < c[i-1][j]){ c[i][j] = c[i-1][j]; } } } return c; } public static void print(int [][]outarr,String x,String y){ for(int i = 0;i < x.length()+1;i++){ for(int j = 0; j < y.length()+1;j++){ System.out.print(outarr[i][j] + " "); } System.out.println(); } } /* 输出字符串 */ public static void getLcstring(String x,String y,int [][]c){ /* 此处不能使用两个for循环,因为两次for循环是分别进行m*n的遍历,使用一个for循环两个条件,是要一个不满足就break。 */ for(int i = x.length(), j = y.length();i>=1 && j>=1;){ if(x.charAt(i-1) == y.charAt(j-1)){ System.out.println("element: " + x.charAt(i-1) + "\t" + " i: " + i + " j: "+j); i--; j--; }else if(c[i-1][j] >= c[i][j-1]){ i--; }else if(c[i-1][j] < c[i][j-1]){ j--; } } } public static void main(String[] args) { // TODO Auto-generated method stub String a = "ABCBDABfsdgsfdr"; String b = "BDCABAr"; int [][]result = lcs(a,b); print(result,a,b); System.out.println(result); getLcstring(a,b,result); System.out.println("-----end---"); }}
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 1 1 1 1 2 2 2 0 1 1 2 2 2 2 2 0 1 1 2 2 3 3 3 0 1 2 2 2 3 3 3 0 1 2 2 3 3 4 4 0 1 2 2 3 4 4 4 0 1 2 2 3 4 4 4 0 1 2 2 3 4 4 4 0 1 2 2 3 4 4 4 0 1 2 2 3 4 4 4 0 1 2 2 3 4 4 4 0 1 2 2 3 4 4 4 0 1 2 2 3 4 4 4 0 1 2 2 3 4 4 5 [[I@1db9742element: r i: 15 j: 7element: A i: 6 j: 6element: B i: 4 j: 5element: C i: 3 j: 3element: B i: 2 j: 1-----end---
阅读全文
0 0
- 最长公共子序列 LCS DP
- DP 最长公共子序列 LCS
- DP---LCS 最长公共子序列问题
- DP之最长公共子序列 LCS
- 最长公共子序列(LCS DP)
- 最长公共子序列LCS(DP)
- 最长公共子序列LCS-DP
- ACM DP 最长公共子序列Lcs
- 最长公共子序列Lcs (dp)
- LCS 求最长公共子序列 dp
- LCS:最长公共子序列
- LCS---最长公共子序列
- 最长公共子序列 LCS
- LCS -- 最长公共子序列
- LCS最长公共子序列
- 最长公共子序列LCS
- LCS-最长公共子序列
- 最长公共子序列 LCS
- robotframework的mac版本安装
- Layui自定义模块基础学习
- Docker Swarm 和Swarm mode 是两个概念!!
- nagios安装使用指南
- 设计模式->行为型模式->迭代器模式
- 最长公共子序列LCS-DP
- TCP的三次握手四次分手详解
- input标签的method属性 post与get的区别
- 通过nginx访问静态文件配置
- Qt实现TCP通信简例
- 1012: [JSOI2008]最大数maxnumber 单调栈+二分
- printf开启关闭宏-方便调试
- AttributeError: module 'urllib' has no attribute 'urlopen'
- webService开发02