Reputation: 2106
Assume I have two strings:
a = 'stackoverflow'
b = 'mathisgoodstackover'
I try to find the largest overlap part from the beginning of a
that match the ending of b
.
c= 'stackover'
d = 'stackoverf'
c
is the optimal solution. d
is not, since the b
does not end with stackoverf
.
I try to use brute-force, but not sure how to write the loop. any efficient algorithm?
Thanks,
Upvotes: 0
Views: 40
Reputation: 17322
you can use the built-in function max
with a list comprehension:
max([a[:i] for i in range(1,len(a) + 1) if b.endswith(a[:i])], key=len)
output:
'stackover'
also for special cases:
a = 'ssss'
b = 'mathisgoodssssss'
max([a[:i] for i in range(1,len(a) + 1) if a[:i] == b[-i:]], key=len)
outut:
'ssss'
or as suggested by @ShadowRanger you could start with i
large as possible and then shrinking using next built-in function with a generator expression
next((a[:i] for i in range(len(a), 0,-1) if b.endswith(a[:i])), '')
Upvotes: 2