码迷,mamicode.com
首页 > 其他好文 > 详细

使用动态规划计算最长公共子串

时间:2018-12-05 18:35:34      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:rac   char   计算   mat   length   oid   abc   cte   print   

public class MatchStr { public static String a="abcdfishftfuia345345345"; public static String b="foshdguuuutfu345345345abcd"; public static void main(String [] arg){ char[] c1= a.toCharArray(); char[] c2 = b.toCharArray(); int [] [] all=new int[c1.length][c2.length]; for(int i=0; i<c1.length; i++){ for(int j=0; j<c2.length; j++){ all[i][j]=0; } } List<Character> list=new ArrayList<>(); for(int i=0; i<c1.length; i++){ for(int j=0; j<c2.length; j++){ if(c1[i]==c2[j]){ int a1=i-1; if(a1<0){ a1=0; } int b1=j-1; if(b1<0){ b1=0; } all[i][j]=all[a1][b1]+1; }else{ all[i][j]=0; } } } int maxx=0; int maxy=0; int max=0; for(int i=0; i<c1.length; i++){ for(int j=0; j<c2.length; j++){ if(all[i][j]>max){ maxx=i; maxy=j; max=all[i][j]; } } } System.out.println(max+"->"+maxx+"->"+maxy); for(int i=0; i<max; i++){ list.add(c1[maxx-i]); } Collections.reverse(list); for(int i=0; i<list.size(); i++){ System.out.print(list.get(i)); } } }

使用动态规划计算最长公共子串

标签:rac   char   计算   mat   length   oid   abc   cte   print   

原文地址:http://blog.51cto.com/12597095/2326486

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!