Given two strings, find the longest common substring. Return the length of it. Note The characters in substring should occur continiously in original string. This is different with subsequnce. Example Given A=“ABCD”, B=“CBCE”, return 2
1 public class Solution { 2 /** 3 * @param A, B: Two strings. 4 * @return: The length of longest common subsequence of A and B. 5 */ 6 public int longestCommonSubstring(String A, String B) { 7 // write your code here 8 int[][] res = new int[A.length()+1][B.length()+1]; 9 int result = 0; 10 for (int i=0; i<=A.length(); i++) { 11 for (int j=0; j<=B.length(); j++) { 12 if (i==0 || j==0) { 13 res[i][j] = 0; 14 continue; 15 } 16 if (A.charAt(i-1) != B.charAt(j-1)) res[i][j] = 0; 17 else res[i][j] = res[i-1][j-1]+1; 18 result = Math.max(result, res[i][j]); 19 } 20 } 21 return result; 22 } 23 }