您的位置:首页 > 其它

最长公共子串(连续)

2015-08-12 17:29 363 查看
题目标题:计算两个字符串的最大公共字串的长度,字符不区分大小写

代码如下:

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
String[] ss = str.split(" ");
String s1 = ss[0];
String s2 = ss[1];
int result = longSubstring(s1,s2);
System.out.println(result);
}
public static int longSubstring(String s1,String s2){

if(s1==null||s1.equals("")||s2==null||s2.equals("")){
return 0;
}
s1 = s1.toUpperCase();
s2 = s2.toUpperCase();

int len1 = s1.length();
int len2 = s2.length();

int[][] result = new int[len2][len1];

for(int i=0;i<len1;i++){
if(s2.charAt(0)==s1.charAt(i)){
result[0][i] = 1;
}
}
for(int j=0;j<len2;j++){
if(s1.charAt(0)==s2.charAt(j)){
result[j][0] = 1;
}
}

for(int i=1;i<len2;i++){
for(int j=1;j<len1;j++){
if(s1.charAt(j)==s2.charAt(i)){
result[i][j] = result[i-1][j-1]+1;
}
}
}

int max = 0;
for(int i=1;i<len2;i++){
for(int j=1;j<len1;j++){
if(result[i][j]>max){
max  = result[i][j];
}
}
}

return max;

}

}
思路参考博客:
http://www.cnblogs.com/zhangchaoyang/articles/2012070.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: