public class Solution {
/**
* longest common substring
* @param str1 string字符串 the string
* @param str2 string字符串 the string
* @return string字符串
*/
public String LCS (String str1, String str2) {
// write code here
if(str1 == null || str2 == null){
return null;
}
int m = str1.length();
int n = str2.length();
//dp[i][j] 代表 0...i-1 到 0....j-1 以 i-1 和 j-1为尾的公共子串长度
int[][] dp = new int[m+1][n+1];
//max 最长公共子串长度
int max = 0,end = 0;
for(int i = 0 ;i< m;i++){
for(int j = 0;j< n;j++){
if(str1.charAt(i) == str2.charAt(j)){
dp[i+1][j+1] = dp[i][j]+1;
if(max < dp[i+1][j+1]){
max = dp[i+1][j+1];
end = i+1;
}
}
}
}
return max ==0 ? "-1":str1.substring(end - max ,end);
}
}