forked from tmjnow/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest_common_subsequence.py
More file actions
28 lines (25 loc) · 674 Bytes
/
longest_common_subsequence.py
File metadata and controls
28 lines (25 loc) · 674 Bytes
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
"""
Given string a and b, with b containing all distinct characters,
find the longest common subsequence's
length. Expected complexity O(nlogn).
"""
def max_common_sub_string(s1, s2):
# Assuming s2 has all unique chars
s2dic = {s2[i]: i for i in xrange(len(s2))}
maxr = 0
subs = ''
i = 0
while i < len(s1):
if s1[i] in s2dic:
j = s2dic[s1[i]]
k = i
while j < len(s2) and k < len(s1) and s1[k] == s2[j]:
k += 1
j += 1
if k - i > maxr:
maxr = k-i
subs = s1[i:k]
i = k
else:
i += 1
return subs