算法实现-->最长子序列问题
来源:互联网 发布:汽车英文翻译软件 编辑:程序博客网 时间:2024/06/06 15:03
/* * 最长子序列 */public class LCS {int [][]c;public static void main(String[]args){String str1="ABCBDAB";String str2="BDCABA";LCS lcs=new LCS();char[][]b=lcs.getLCS(str1, str2);lcs.printB(b, str1.length()-1, str2.length()-1);}public void printB(char [][]b,int i,int j){ if(i==-1||j==-1)return; if(b[i][j]=='↖'){ printB(b,i-1,j-1); System.out.println(i); }else if(b[i][j]=='←'){ printB(b,i,j-1); }else if (b[i][j]=='↑'){ printB(b,i-1,j); }}public char [][] getLCS(String str1,String str2){ c=new int[str1.length()][str2.length()]; char[][]b=new char[str1.length()][str2.length()]; ///初始化 if(str1.charAt(0)==str2.charAt(0)){ c[0][0]=1; }else{ c[0][0]=0; } for(int i=0;i<str1.length();i++){ for(int j=0;j<str2.length();j++){ b[i][j]='0'; } } for(int i=0;i<str1.length();i++){ if(str1.charAt(i)==str2.charAt(0)){ c[i][0]=1; b[i][0]='↖'; }else{ c[i][0]=0; b[i][0]='0'; } } for(int j=0;j<str2.length();j++){ if(str1.charAt(0)==str2.charAt(j)){ c[0][j]=1; b[0][j]='↖'; }else{ c[0][j]=0; b[0][j]='0'; } } for(int i=1;i<str1.length();i++){ for(int j=1;j<str2.length();j++){ if(str1.charAt(i)==str2.charAt(j)){ c[i][j]=c[i-1][j-1]+1; b[i][j]='↖';//指向左对角线位置 }else{ if(c[i-1][j]>=c[i][j-1]){ c[i][j]=c[i-1][j]; b[i][j]='↑';//向上移动 }else{ c[i][j]=c[i][j-1]; b[i][j]='←';//向左移动 } } } } for(int i=0;i<str1.length();i++){ for(int j=0;j<str2.length();j++){ System.out.print( b[i][j]+" "); } System.out.println(); } return b;}}
0 0
- 算法实现-->最长子序列问题
- 最长公共子序列算法问题
- 《算法导论》最长子序列问题
- 最长上升子序列LIS算法实现
- 最长上升子序列LIS算法实现
- 动态规划算法----实现最长子序列
- 最长上升子序列LIS算法实现
- 最长上升子序列LIS算法实现
- 最长上升子序列LIS算法实现
- 判断子序列、求最长公共子序列算法实现
- 最长公共子序列问题Python实现
- 最长子序列问题
- 最长子序列问题
- 最长子序列问题
- 最长子序列问题
- 【经典算法】:最长公共子序列(LCS问题,用遍历实现)
- 动态规划算法——最长公共子序列问题(java实现)
- 经典算法实现(最长公共子序列,最长递增子序列)
- while(cin >> v) demo
- linux 文件查找
- 追逐自己的梦想----------辅助制作第十七课:实现技能列表的遍历及判断技能是否可用
- Myeclipse 2014的ssh整合出错java.lang.NoSuchMethodError: antlr.collections.AST.getLine()
- springmvc的特性
- 算法实现-->最长子序列问题
- 实现操作符重载的两种方式
- ImageView.ScaleType
- ACM-BestCoder Round #33
- const 用法总结
- 代码备忘, TODO宏实现
- 优先队列priority_queue 用法详解
- 第二周项目二--长方柱类
- 杭电ACM1010——深度优先搜索+奇偶剪枝