面试题:最长公共子串
难度:中等
给出两个字符串,找到最长公共子串,并返回其长度。
样例
给出A=“ABCD”,B=“CBCE”,返回 2。
A=“www.lintcode.com code”,B=“www.ninechapter.com code”,返回 9。
注意
子串的字符应该连续的出现在原字符串中,这与子序列有所不同。
答案:
1 public class Solution { 2 /** 3 * @param A, B: Two string. 4 * @return: the length of the longest common substring. 5 */ 6 public int longestCommonSubstring(String A, String B) { 7 // write your code here 8 int maxlen = 0; 9 int xlen = A.length(); 10 int ylen = B.length(); 11 for(int i = 0; i < xlen; ++i) 12 { 13 for(int j = 0; j < ylen; ++j) 14 { 15 int len = 0; 16 while (i + len < xlen && j + len < ylen && 17 A.charAt(i + len) == B.charAt(j + len)) 18 len ++; 19 if(len > maxlen) 20 maxlen = len; 21 } 22 } 23 return maxlen; 24 } 25 }