*Longest Common Substring

Given two strings, find the longest common substring.

Return the length of it.

Example

Given A = "ABCD", B = "CBCE", return 2.

Note

The characters in substring should occur continuously in original string. This is different with subsequence.

Challenge

O(n x m) time and memory.

 

分析:

九章算法模板:

 

 1 /**
 2  * 本代码由九章算法编辑提供。没有版权欢迎转发。
 3  * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
 4  * - 现有的面试培训课程包括:九章算法班,系统设计班,BAT国内班
 5  * - 更多详情请见官方网站:http://www.jiuzhang.com/
 6  */
 7 
 8 public class Solution {
 9     /**
10      * @param A, B: Two string.
11      * @return: the length of the longest common substring.
12      */
13     public int longestCommonSubstring(String A, String B) {
14         // write your code here
15         int maxlen = 0;
16         int xlen = A.length();
17         int ylen = B.length();
18         for(int i = 0; i < xlen; ++i)
19         {
20             for(int j = 0; j < ylen; ++j)
21             {
22                 int len = 0;
23                 while (i + len < xlen && j + len < ylen && 
24                     A.charAt(i + len) == B.charAt(j + len))
25                         len ++;
26                 if(len > maxlen)
27                     maxlen = len;
28             }
29         }
30         return maxlen;
31     }
32 }

 

posted @ 2015-09-25 11:04  Hygeia  阅读(231)  评论(0编辑  收藏  举报