Longest Common Substring
2016-05-26 15:17
232 查看
有了前面Longest Common Subsequence的练习,这个题可以照葫芦画瓢,但是要注意的是,是什么的值可以传递,最后要返回的值是存在哪里的。
1. 这个是求子字符串,必须是连续的,即,如果i和j匹配,值只能从i-1,j-1处得到,再加一,如果不匹配,[i][j]即为0,不可传递。
2. 最大值是单独保存的,因为最大值无法在数组中持续传递
public class Solution {
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
public int longestCommonSubstring(String A, String B) {
// write your code here
int al = A.length();
int bl = B.length();
int lcsCount = 0;
int [][]lcs = new int[al+1][bl+1];
for (int i = 1; i <= al; i++) {
for (int j = 1; j <= bl; j++) {
if (A.charAt(i-1)==B.charAt(j-1)) {
lcs[i][j] = lcs[i-1][j-1] + 1;
if (lcs[i][j] > lcsCount) {
lcsCount = lcs[i][j];
}
}
}
}
return lcsCount;
}
}
下面是另一种做法
public int longestCommonSubstring(String A, String B) {
// int la = A.length();
// int lb = B.length();
// int longestL = 0;
// for(int i=0;i<la;i++){
// for(int j=0;j<lb;j++){
// int len = 0;
// while(i+len<la&&j+len<lb&&A.charAt(i+len)==B.charAt(j+len)){
// ++len;
// if(longestL<len)
// longestL = len;
// }
// }
// }
// return longestL;
}
1. 这个是求子字符串,必须是连续的,即,如果i和j匹配,值只能从i-1,j-1处得到,再加一,如果不匹配,[i][j]即为0,不可传递。
2. 最大值是单独保存的,因为最大值无法在数组中持续传递
public class Solution {
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
public int longestCommonSubstring(String A, String B) {
// write your code here
int al = A.length();
int bl = B.length();
int lcsCount = 0;
int [][]lcs = new int[al+1][bl+1];
for (int i = 1; i <= al; i++) {
for (int j = 1; j <= bl; j++) {
if (A.charAt(i-1)==B.charAt(j-1)) {
lcs[i][j] = lcs[i-1][j-1] + 1;
if (lcs[i][j] > lcsCount) {
lcsCount = lcs[i][j];
}
}
}
}
return lcsCount;
}
}
下面是另一种做法
public int longestCommonSubstring(String A, String B) {
// int la = A.length();
// int lb = B.length();
// int longestL = 0;
// for(int i=0;i<la;i++){
// for(int j=0;j<lb;j++){
// int len = 0;
// while(i+len<la&&j+len<lb&&A.charAt(i+len)==B.charAt(j+len)){
// ++len;
// if(longestL<len)
// longestL = len;
// }
// }
// }
// return longestL;
}
相关文章推荐
- 关于Java 中的 i += 1 和 i = i + 1 问题
- idea 代码自动提示快捷键自动提示冲突问题
- 【elasticsearch】elasticsearch 2.x 环境搭建以及常用插件(head,hq,ik)安装
- android DES加密
- iOS开发之使用Storyboard预览UI在不同屏幕上的运行效果
- C和C++编译器的函数名修饰规则
- js获取其他页面的变量
- Hibernate Annotation
- SQL sERVER 2008 创建数据库
- catkin创建一个ROS包
- 欢迎使用CSDN-markdown编辑器
- iOS 一种很方便的构造TarBar
- C++实践参考:两个成员的类模板
- java.net.SocketException: No buffer space available
- sql server base64解密函数
- Python学习笔记之字典
- redis 持久化的两种方式
- DisplayImageOptions 设置图片显示的类。
- mysqld启动“ Can't start server: Bind on TCP/IP port: Address already in use Do you already have anothe
- JAVA调用系统命令或可执行程序