Lintcode: Longest Common Substring 解题报告

本文深入探讨了寻找两个字符串中最长公共子串的问题,通过动态规划方法详细解释了算法的实现过程,包括状态转移方程和代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Longest Common Substring

原题链接: http://lintcode.com/zh-cn/problem/longest-common-substring/#

Given two strings, find the longest common substring.

Return the length of it.

注意

The characters in substring should occur continiously in original string. This is different with subsequnce.

样例
 

标签 Expand 

 

SOLUTION 1:

DP:
D[i][j] 定义为:两个string的前i个和前j个字符串,尾部连到最后的最长子串。
D[i][j] = 
1. i = 0 || j = 0 : 0
2. s1.char[i - 1] = s2.char[j - 1] ? D[i-1][j-1] + 1 : 0;
另外,创建一个max的缓存,不段更新即可。
 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         if (A == null || B == null) {
 9             return 0;
10         }
11         
12         int lenA = A.length();
13         int lenB = B.length();
14         
15         // bug 1: use error init.
16         int[][] D = new int[lenA + 1][lenB + 1];
17         
18         int max = 0;
19         
20         // BUG 2: should use <= instead of <
21         for (int i = 0; i <= lenA; i++) {
22             for (int j = 0; j <= lenB; j++) {
23                 if (i == 0 || j == 0) {
24                     D[i][j] = 0;
25                 } else {
26                     if (A.charAt(i - 1) == B.charAt(j - 1)) {
27                         D[i][j] = D[i - 1][j - 1] + 1;
28                     } else {
29                         D[i][j] = 0;
30                     }
31                 }
32                 
33                 max = Math.max(max, D[i][j]);
34             }
35         }
36         
37         return max;
38     }
39 }
View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/dp/LongestCommonSubstring.java

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值