码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode-Longest Common Substring

时间:2015-01-01 00:01:16      阅读:339      评论:0      收藏:0      [点我收藏+]

标签:

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.

Solution:

 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         int lenA = A.length();
 8         int lenB = B.length();
 9         if (lenA==0 || lenB ==0 ) return 0;
10 
11         int[][] lcs = new int[lenA+1][lenB+1];
12         for (int i=0;i<=lenA;i++) lcs[i][0] = 0;
13         for (int i=0;i<=lenB;i++) lcs[0][i] = 0;
14 
15         int res = 0;
16         for (int i=1;i<=lenA;i++)
17             for (int j=1;j<=lenB;j++)
18                 if (A.charAt(i-1)==B.charAt(j-1)){
19                     lcs[i][j]=lcs[i-1][j-1]+1;
20                     if (lcs[i][j]>res) res = lcs[i][j];
21                 } else lcs[i][j]=0;
22 
23         return res;
24     }
25 }

 

LintCode-Longest Common Substring

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/4196793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!