Problem Statement:
Given two strings S1 and S2, find the longest common substring between S1 and S2.
Approach 1: Dynamic Programming
def LCS(s1, s2):
"""
Time complexity: O(n^2)
Space complexity: O(n^2)
"""
if not s1 or not s2:
return 0
n, m = len(s1), len(s2)
dp = [[0 for i in xrange(m + 1)] for j in xrange(n + 1)]
lcs_length, lcs_end_index = 0, 0
for i in xrange(1, n + 1):
for j in xrange(1, m + 1):
if s1[i - 1] == s2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
if dp[i][j] > lcs_length:
lcs_length = dp[i][j]
lcs_end_index = i
return lcs_length, s1[lcs_end_index - lcs_length : lcs_end_index]
if __name__ == "__main__":
s1 = "LCLC"
s2 = "CLCL"
assert LCS(s1, s2) == (3, 'LCL')
print "All test cases have passed! :)"