public String LCS (String str1, String str2) { int max = 0; //存储中间值 int[][] p = new int[str1.length()][str2.length()]; StringBuilder temp = new StringBuilder(); int pos = 0; for (int i = 0 ; i < str1.length(); i++) { for (int j = 0 ; j < str2.length(); j++) { if(str1.charAt(i) == str2.charAt(j)){ if(i == 0 || j==0){ p[i][j] = 1; }else{ p[i][j] = p[i-1][j-1] + 1; } } if(max <= p[i][j]){ max = p[i][j]; pos = i; } } } return str1.substring(pos-max+1,pos+1); }
总结:
动态规划的关键在于 用中间容器存放每次迭代的中间结果
循环比递归调用的执行效率更高
标签:子串,String,--,str2,str1,int,length,new,最长 From: https://www.cnblogs.com/yanher/p/16839408.html