问题描述:
对于两个字符串,求出两串的最长公共子串的长度(要求连续)
输入:
"1AB2345CD",9,"12345EF",7
输出:
4
用二维数组保存状态,dp[i][j]表示最长公共子串长度,
如果str1[i] = =str2[j], dp[i][j] = dp[i-1][j-1]+1;
用max保存最大值
public static int findLongest(String A, int n, String B, int m) {
// write code here
int[][] dp = new int[n][m];
for(int i=0;i<n;i++){
if(A.charAt(i)==B.charAt(0)){
dp[i][0] = 1;
}
}
for(int i=0;i<m;i++){
if(A.charAt(0)==B.charAt(i)){
dp[0][i] = 1;
}
}
int max = Integer.MIN_VALUE;
for(int i=1;i<n;i++){
for(int j=1;j<m;j++){
if(A.charAt(i)==B.charAt(j)){
dp[i][j] = dp[i-1][j-1]+1;
max = Math.max(max, dp[i][j]);
}
}
}
return max;
}