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

LintCode Longest Common Substring

时间:2016-04-03 14:27:29      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:http://www.lintcode.com/en/problem/longest-common-substring/#

题目:

Given two strings, find the longest common substring.

Return the length of it.

Example

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

Challenge

O(n x m) time and memory.

题解:

Longest Common Subsequence相似.

DP. 参考http://www.geeksforgeeks.org/longest-common-substring/

dp[i][j]表示长度为i的str1 和 长度为j的str2 longest common substring长度.

看两个substring 的 suffix.

dp[i][j] = dp[i-1][j-1] + 1 if str1.charAt(i-1) == str2.charAt(j-1).

dp[i][j] = 0. o.w

Time Complexity: O(m*n). Space: O(m*n).

AC Java:

 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         if(A == null || B == null){
 8             return 0;
 9         }
10         int m = A.length(); 
11         int n = B.length();
12         int [][] dp = new int[m+1][n+1];
13         int longest = 0;
14         for(int i = 1; i<=m; i++){
15             for(int j = 1; j<=n; j++){
16                 if(A.charAt(i-1) == B.charAt(j-1)){
17                     dp[i][j] = dp[i-1][j-1]+1;
18                 }else{
19                     dp[i][j] = 0;
20                 }
21                 longest = Math.max(longest, dp[i][j]);
22             }
23         }
24         return longest;
25     }
26 }

 

LintCode Longest Common Substring

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5349760.html

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