-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path79.longest-common-substring.py
66 lines (61 loc) · 1.32 KB
/
79.longest-common-substring.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Tag: Dynamic Programming/DP, Two Sequences DP
# Time: O(NM)
# Space: O(NM)
# Ref: -
# Note: -
# Given two strings, find the longest common substring.
#
# Return the length of it.
#
# **Example 1:**
#
# Input:
# ```
# stringA = "ABCD"
# stringB = "CBCE"
# ```
# Output:
# ```
# 2
# ```
# Explanation:
#
# Longest common substring is "BC"
#
# **Example 2:**
#
# Input:
# ```
# stringA = "ABCD"
# stringB = "EACB"
# ```
# Output:
# ```
# 1
# ```
# Explanation:
#
# Longest common substring is 'A' or 'C' or 'B'
#
# The characters in **substring** should occur continuously in original string. This is different with **subsequence**.
class Solution:
"""
@param a: A string
@param b: A string
@return: the length of the longest common substring.
"""
def longest_common_substring(self, a: str, b: str) -> int:
# write your code here
n = len(a)
m = len(b)
dp = [[0] * m for i in range(n)]
res = 0
for i in range(n):
for j in range(m):
if a[i] == b[j]:
if i > 0 and j > 0:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = 1
res = max(res, dp[i][j])
return res